Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiple threads and local members  RSS feed

 
Cory Wilkerson
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assume a single instance of TestObject:

Is the above code by nature thread safe (I've got a developer telling me that it is because it's all local to the method and every thread has it's local stack)? I fear that it's not...doesn't seem like an atomic operation to me.
Any input?
 
Michael Bronshteyn
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, this code is thread safe. each method gets created on thread's stack. even if this method would be static, it is still thread-safe.
for reference check the book:
"Inside The Java Virtual Machine"
by Bill Venners
it has a good chapter on the topic
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Things get more interesting talking about reference variables.
A) If the paremeters to the method are objects, either the method should be properly synchronized, or copies of the objecs should be made. These could be done by the caller, or inside the method itself. The caller could even past primitives and the method would construct an object with them --supposing the object has only fields of primitive type--
B) If the object of concern is local to the method, the method is safe thread unless it lets the reference to the object to scape from the method. Though it could do so when it has done with the object.
Concurrent Programming in Java by Dough Lea is a terrific book about the matter.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a thread unsafe version maybe it will shed you some light.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!