5. 0.2 JVM 메모리구조
1. Method Area
- 클래스파일을 읽고, 분석 정보를 저장 (+클래스변수도 여기생성)
2. heap Area
- 모든 인스턴스가 생성되는 공간.인스턴스 변수들이 생성되는곳
3. stack Area
- 메서드 작업에 필요한 메모리공간제공,순차적
[main//fistMehtod//secondMethod….]
6. 0.3 Static
1. 멤버변수 중 공통으로 사용한곳에 Static 변수 사용
2. Static 변수/메소드는 instance가 아니어도 사용가능
4. method내에 인스턴스변수를 사용하지 않을경우 Static을 붙이는것을 고려
3. Static Mehod는 인스턴스 변수(멤버변수) 사용 불가
7. +0.4 SingleTon
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance(){
return instance;
}
}
1. //생성자를 private ==> new해서 만들길 없게끔
//static한 instance를 만듦 ==> getInstance할
때 같은 static instance를 리턴
=> Static 하기때문에 사용하지않아도 메모리에 올라며 낭비.
8. public class Singleton {
private static Singleton instance;
private Singleton() {
}
public synchronized static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
2.// 인스턴스의 null여부를 판단하여 처음 생성된 인스턴스를 반환.
// multiThread safe하게 처리하기위해 synchronized를 사용.
=> 스레드가 여러개일경우. getInstance를 호출할떄마다 동기화되어 성능 저하
즉, 매 쓰레드마다 인스턴스를 생성되어 무리다.
스레드 가 어떻게 접근하든 synchronized되어서 만들어짐
+0.4 SingleTon
9. public class Singleton {
private volatile static Singleton instance;
private Singleton() {
}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
3.// DoubleChacking -> 인스턴트가 널? => 동기화하여 인스턴스생
성-> 그외의경우 있는 인스턴스 리턴
=> Reflection과 Serialization 으로 다른 문제를 발생시킬수있다.
스레드가 A가 들어가고 뉴해서 만들어지면 최신 버전(new)
된것이 업데이트되고(volatile로 원자성 보장) 스레드B가 들어가면
보장된 상태로 들어가기때문에 바로 instance
Return 됨.
+0.4 SingleTon
10. 4.//Enum 을 이용한 singelton
=> Serialization 으로 문제를 발생시킬수있다.
enum Singleton
{
INSTANCE;
public static Singleton getInstance()
{
System.out.println("make SingleTOn");
return INSTANCE;
}
}
+0.4 SingleTon