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?
Utility.stringToInt()
s
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.
Integer.parseInt()
Java , synchronized.
synchronized
, , Mutex Class, , , - "" .
. , ; , . , Integer.parseInt(s) , s .
Integer.parseInt(s)
, Integer.parseInt(...) ( parseInt, . , Java , .
, , , . ( )
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. } } }
, , , .
, . , , "s" , .
, s .
, , . s , .
Source: https://habr.com/ru/post/1584989/More articles:Json binding leads to high performance for asp.net mvc 4 - c #highcharts with mvc c # and sql - c #Scope: Iterating a RealmObject and clearing the ArrayList field - javaDeep copying with ProtoBuf in C / C ++ - c ++Два потока, отделенные в одно и то же время и доступ к одному и тому же методу - javaHow to print factorials 0-30 on the table - javaRecursion and return keyword - javaI have two units and a class in each module that each other needs to work. How to avoid a circular link? - delphiEclipse С++ GDB отладчик для Mac - c++Why is a string passed as a constant string in a function parameter - c ++All Articles