Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Concern about Thread safety  RSS feed

 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 159
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thnx! I didn't notice that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!