| Author |
Concern about Thread safety
|
Dennis Grimbergen
Ranch Hand
Joined: Nov 04, 2009
Posts: 126
|
|
Hi guys,
I'm not sure about the thread safety of one of my classes. Here is some code.
I assume it's Thread safe, but I'm just not sure. Can someone confirm or comment on this?
|
SCJP, SCWCD, SCJD
|
 |
Ireneusz Kordal
Ranch Hand
Joined: Jun 21, 2008
Posts: 423
|
|
Hi,
it's not thread safe.
You must synchronize access to getInstance method.
In case when your singleton is not yet initialized (threadSafety == null) and two (or more) threads call getInstance method at the same time,
there is a chance that two (or more) singletons will be created.
To make this code thread safe either getInstance must be synchronized or singleton object must be created in the static initialization block like that:
|
 |
Dennis Grimbergen
Ranch Hand
Joined: Nov 04, 2009
Posts: 126
|
|
|
Thnx! I didn't notice that.
|
 |
 |
|
|
subject: Concern about Thread safety
|
|
|