This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes thread-safe methods 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 "thread-safe methods" Watch "thread-safe methods" New topic
Author

thread-safe methods

Theo Jenks
Greenhorn

Joined: Oct 25, 2001
Posts: 1
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

Joined: Apr 20, 2000
Posts: 3252
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).]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: thread-safe methods
 
Similar Threads
String and StringBuffer
StringBuffer Instance Variable
K&B SelfTest Ques ,chap 9 pg 739
my thread and synchronized
simple J2EE question