Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent access of Singleton in java

I have a sinlgeton object which holds one method, witch is NOT synchronized. The singleton can be accessed by many clients at a time - what will happen if multiple clients access that object ? Will the object reference be provided to them in a First come- first serve manner...that is, would one client have to wait for the first one to finish the object, or it will be given the same object reference in memory ?

I get a weird feeling about the method in the singleton which is not synchronized. If 2 clients call Singleton.method(param), with different params - they wont create problems for each other right ?

like image 502
WinOrWin Avatar asked Dec 27 '22 16:12

WinOrWin


2 Answers

If your method does not use any shared state (e.g. singleton fields), this is completely safe. Method parameters are passed on the thread stack - which is local and exclusive to the stack.

Think about two processors running the same code but operating on different areas in memory.

like image 74
Tomasz Nurkiewicz Avatar answered Dec 30 '22 07:12

Tomasz Nurkiewicz


Singleton means that there should be only one instance of the class. Well, this may not be true if the singleton is not properly implemented. Safest way of having a singleton is to declare it as an enum.

If there's a method that's not synchronized it means that multiple threads can execute the body of the method in the same time. If the singleton is immutable then there's no worry. Otherwise you should pay attention to possible inconsistencies. One thread can change a state while the other one is doing the same resulting in unpredictable outcome very hard to debug.

like image 25
Boris Pavlović Avatar answered Dec 30 '22 05:12

Boris Pavlović