0

Will the following singleton class code cause any problems in multithreading environment?

public class mySingletonClass{  

    private static mySingletonClass INSTANCE = new mySingletonClass();      

    private mySingletonClass() 
    {       
        super();    
    }   

    public static mySingletonClass getInstance() 
    {       
        return INSTANCE;    
    }
}
Emily
  • 1
  • The class doesn't seem to be doing anything. Could you elaborate on what problems would you be expecting? Did you leave some information out of the question, like a shared resource the class is encapsulating? – Mick Mnemonic Oct 09 '18 at 19:19
  • It is thread safe concerning the singleton instantiation/retrieval as you initialize the instance eagerly in the initializer that is thread safe de facto. But actually your singleton provides no behavior. Please provide behavioral methods for your class and we could judge whether these are thread safe. – davidxxx Oct 09 '18 at 19:21

2 Answers2

2

The above code should not cause any issue in multithreaded environment as the INSTANCE gets created during the class is loaded and it will be only once.

Any time you call getInstance() even if it is concurrent should not cause any issue.

rahul shetty
  • 126
  • 7
0

The main reason that this class is thread-safe is because there are no resources in this class which can be shared among multiple threads. For example instance variables.

This class is singleton as JVM will create only single object for this class when the class is loaded by calling mySingletonClass.getInstance() first time. Now every time this method is called same instance will be returned. But now consider the following scenario:

public class mySingletonClass{ 

    int x;

    public vois setX(int x){
        this.x = x;
    }

    public int getX(){
        return x;
    }

    private static mySingletonClass INSTANCE = new mySingletonClass();      

    private mySingletonClass() 
    {       
        super();    
    }   

    public static mySingletonClass getInstance() 
    {       
        return INSTANCE;    
    }
}

Now there is an instance variable x. Now since this class is singleton so same object will be shared among multiple threads and that means same instance variable x. Now you can't be sure that the different threads are accessing the correct value of x. Then you have to use different ways so that at a time only one thread accesses the shared resources which is x in the above case. For that you can either make the setX(int x) and getX() method synchronized or can create an object LOCK which will ensure that at a time only one thread mutate the variable x.

Yug Singh
  • 3,112
  • 5
  • 27
  • 52