I have this static block of code which is following Singleton design pattern.

class Employee{
    private static Employee emp;

    static {
    if (emp==null){
       emp=new Employee();
      }
    }

    public static Employee getEmployee(){
       return emp;
    }

}

My doubt is if this code can be accessed by Mutiple threads concurrently and break the singleton logic.
Is it posible initially that when multiple threads try to load the employee object run the static code concurrenctly? and then break the singleton mechanism in the code?

Recommended Answers

All 5 Replies

Please consider my apologies here. I forgot to add the private constructor , so the modified complete code should be

class Employee{  
    private Employee(){}
    private static Employee emp; 


    static {    
        if (emp==null){
        emp=new Employee(); 
    }    
        }    
    public static Employee getEmployee(){   
        return emp;  
        }
}

Quoted Text Here
My doubt still remains same

The static block will be executed before a constructor, or any other method, can be accessed, so I believe that there should be no thread-related problems (JLS 12.4.1)

It doesn't seem to break your block, but it may give you an unintentional result if you allow modification of the class without synchronize the process anywhere. You need to watch out for that when dealing with multiple threads.

Looking more closely at your code there ia a small problem that may reval some confusion in your thinking:
The if test in the static block is totally redundant because emp is an unitialised static variable, which will always be null when the static initialiser block is executed.

Provided you have no methods that update the emp variable your singleton creation/access code is completely thread-safe. It would help guarantee this if you also declare emp as final.

I have found another way of doing this without having the static block.

class Employee{
    private static Employee emp =new Employee();
    private Employee(){}
    public static Employee getEmployee(){
       return emp;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.