• Post Reply Bookmark Topic Watch Topic
  • New Topic

thread-safe methods

 
Theo Jenks
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is a method inherently thread safe if it only accesses data local to that method (no member fields)? My assumption is that local data is written to the stack of the calling thread, so each thread has its own copy of the local data. Is this correct?
For instance, is the following method thread-safe?
public static String executeLoopOnListIterator(ListIterator collection, String prefix, String suffix) {
StringBuffer htmlBuff = new StringBuffer();
while(collection.hasNext()) {
htmlBuff.append(prefix);
htmlBuff.append(collection.next());
htmlBuff.append(suffix);
}
return htmlBuff.toString();
}
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Theo Jenks:
Is a method inherently thread safe if it only accesses data local to that method (no member fields)?
Any stateless class is inherently threadsafe, provided that the objects it accesses are either private to the thread, or threadsafe themselves. The method you gave is threadsafe, but no other thread must be modifying the collection the iterator iterates over, or any of the objects in that collection.
Threading issues arise when two or more threads are accessing, especially modifying, the same state. "State" often means "static or member variables", but this is not necessarily so - creating one object and giving it to multiple threads as a method argument can create just as many problems.
- Peter

[This message has been edited by Peter den Haan (edited October 26, 2001).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!