4

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 ?

WinOrWin
  • 2,107
  • 3
  • 19
  • 25

2 Answers2

7

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Thanks. But I still did not get the point that if there are no 2 objects in the memory (because of singleton), would there be two methods (of the same class) on the stack ? – WinOrWin Jul 29 '11 at 09:12
  • 2
    Your singleton object (its instance fields) is located on the heap. The code of singleton object methods is located on PermGen memory (once per loaded class, not object). Method parameters are passed on stack, local to every thread. Three different memory locations, I suggest you read more about them. – Tomasz Nurkiewicz Jul 29 '11 at 09:21
3

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.

Community
  • 1
  • 1
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148