• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is the following Class Thread Safe ?.  RSS feed

 
Steven Rodeo
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi Folks,

just wondering if the following class Thread Safe ?.



Thanks Much
_SM
 
Istvan Kovacs
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you need to make sure tl is final or at least volatile.
http://www.javamex.com/tutorials/synchronization_final.shtml
http://www.ibm.com/developerworks/java/library/j-jtp06197.html (and others in the series)

Be careful: by creating multiple instances of the class, each instance will have a separate ThreadLocal object, which means each thread will be able to use a separate value for the object stored in the ThreadLocal in each instance of the class; that is, placing something in the ThreadLocal in one thread in one instance will affect neither what another thread reads from the same instance (that's the purpose of ThreadLocal), nor what the same thread will read in another instance.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree on both points. You need to make t1 final (I don't think volatile would make any sense, really) and you need to be aware that each thread will see a different value. If that's your intent, fine. Also, t1 should really be private.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!