jQuery in Action, 2nd edition
The moose likes Threads and Synchronization and the fly likes Concern about Thread safety Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Concern about Thread safety" Watch "Concern about Thread safety" New topic
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Concern about Thread safety
 
Similar Threads
Servlets Netbeans ThreadSafety Easy Question.
threadsafety of a singleton
B&S: Threadsafety & RandomAccessFile
Threadsafety
Doubt in ThreadSafety