If a public method of an object only uses parameters passed, and local variables, then
can we say that it is thread-safe?
If a public method of an object only uses parameters passed, and local variables, then
can we say that it is thread-safe?
A so called pure function is indeed thread safe, but only if there are absolutely no side effects (ie, objects passed in via parameters altered).
Yes, it's thread safe. It can not interfere with invocations of other methods. (Unless it has some other nasty side effects.)
Any interleaving of the instructions of this method, and the instructions of any other method will be ok.
If local memeber variables are not modified and the state of passed parameters is not changed (i.e. via methods on those parameters), then it is thread safe.
Furthermore, if passed parameters are objects, making them final does not guarantee thread safety.
public class Foo{
private int count = 1;
public void incrementFoo(){
count += 1;
}
public int getFoo(){
return count;
}
}
private int multiplier = 5;
//Not safe
public static int calculateFoo(final Foo myFoo){
//you can still do this, even if myFoo is final
myFoo.incrementFoo();
return myFoo.getFoo() * multiplier;
}
It depends. There are ways it can easily be not thread safe.
First, if any argument that is passed into the method is not thread safe and your method uses it in a multi-threaded manner without proper synchronization, it is not thread safe. For example,
// HashMap is not thread safe
public void foo(String key, HashMap<String,String> map) {
String value = map.get(key);
if (value == null) {
map.put(key, "new value");
}
}
Another possibility is if any object that was created within the method escapes the method. Consider the following:
public void foo() {
Map map = ...; // create and populate the map
ListenerQueue.getQueue().add(map); // there are listener threads waiting on this queue
// do some other work
}
If there are other threads that are waiting on this queue and start using the map object, then the map object has escaped, and is subject to the same thread-safety issues.