Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a method does not use object's fields then 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?

like image 408
EugeneP Avatar asked Dec 09 '22 16:12

EugeneP


2 Answers

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

like image 95
Ikke Avatar answered Apr 06 '23 00:04

Ikke


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;
}
like image 34
Emilis Panovas Avatar answered Apr 06 '23 01:04

Emilis Panovas