If the method does not use the fields of the object, is it thread safe?

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

can we say that it is thread safe?

+4
source share
4 answers

And the so-called pure function is really thread safe, but only if there are absolutely no side effects (i.e. objects transmitted through changed parameters).

+9
source

If the memeber local variables do not change and the state of the parameters passed does not change (i.e., using the methods for these parameters), then this is thread safe.

In addition, if the parameters passed are objects, which makes them final, this 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; } 
+3
source

Yes, it is thread safe. It cannot interfere with calls to other methods. (If he has no other unpleasant side effects.)

Any alternation of instructions from this method and instructions from any other method will be fine.

+1
source

It depends. There are ways in which it can be safe for streaming.

Firstly, if any argument that is passed to the method is not thread safe, and your method uses it in a multithreaded way without proper synchronization, it is not thread safe. For instance,

 // 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 that if any object created in the method avoids 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 waiting in this queue and starting to use the map object, then the map object is shielded and is subject to the same thread safety problems.

+1
source

Source: https://habr.com/ru/post/1309397/


All Articles