views:

162

answers:

4

If a public method of an object only uses parameters passed, and local variables, then

can we say that it is thread-safe?

+8  A: 

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).

Ikke
+1  A: 

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.

aioobe
+3  A: 

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;
}
Emilis Panovas
There is no reason to require local variables not to be modified.
Michael Borgwardt
Now when I think about it, I might have missunderstood the question. I thought of local variable as local to the class in which methods is called. What was probably meant - local variable to the scope of the method. In the foo example, I would think of "multiplier" as local.
Emilis Panovas
Typically, `multiplier` would be called a member variable. A local variable is only in scope of the current method being executed as you mention.
laz
Fixed that. Sorry for my incompetence.
Emilis Panovas
A: 

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.

sjlee
All these can be considered "side effects" in the answer above. These are some of the specific examples. It is to illustrate that local method invocations are easier to deal with in terms of thread safety but certainly not immune to it.
sjlee