Java singleton pattern hungry mode code instances

  • 2020-04-01 03:50:01
  • OfStack


class MyThreadScopeData {
 
    //The singleton
    private MyThreadScopeData() {
    }
 
    //Provides methods to get an instance
    public static synchronized MyThreadScopeData getThreadInstance() {
        //Gets an instance object from the current thread-scoped dataset
        MyThreadScopeData instance = map.get();
        if (instance == null) {
            instance = new MyThreadScopeData();
            map.set(instance);
        }
        return instance;
    }
 
    //Stores the instance object in the current thread-scoped dataset
    private static MyThreadScopeData instance = null; //Starvation mode
 
    private String name;
    private int age;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}


Related articles: