Sync related to static method in java

Suppose I have a Utility class,

public class Utility {

    private Utility() {} //Don't worry, just doing this as guarantee.

    public static int stringToInt(String s) {
        return Integer.parseInt(s);
    }
};

Now suppose that in a multi-threaded application, a thread calls a method Utility.stringToInt()and , while the operation enters a method call, another thread calls the same method that passes the other s. What happens in this case? Does Java block the static method?

+3
source share
5 answers

There is no problem. Each thread will use its own stack, so there are no collisions between different ones s. And it Integer.parseInt()is thread safe because it uses only local variables.

+10

Java , synchronized.

, , Mutex Class, , , - "" .

. , ; , . , Integer.parseInt(s) , s .

, Integer.parseInt(...) ( parseInt, . , Java , .

+3

, , , . ( )


public enum Utility {
    ; // no instances

    public synchronized static int stringToInt(String s) {
        // does something which needs to be synchronised.
    }
}

,

public enum Utility {
    ; // no instances

    public static int stringToInt(String s) {
        synchronized(Utility.class) {
            // does something which needs to be synchronised.
        }
    }
}

, , , .

+1

, . , , "s" , .

0

, s .

, , . s , .

0

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


All Articles