Are the following incremental code threads safe in Java?
•
Java
Java code:
public class IncreaseTest { public static int value = 0; public synchronized int increment() { return value++; } }
Is method increment () thread safe? Do I have to add the modifier keyword volatile, as follows:
public static volatile int value = 0;
Solution
This code is not thread safe Instance methods will synchronize on instances. If you have multiple instances, they will not use the same monitor, so updates can be interleaved
You need to remove static from the value field or add static to the increment () method
In addition, since you have exposed the value, there is another problem, that is, you can change or read the value outside this method without using synchronization that may cause the old value to be read
Therefore, changing the code to the following makes it thread safe:
public class IncreaseTest { private int value = 0; public synchronized int increment() { return value++; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码