Is the following incremental stream code safe in java?

Java Code:

public class IncreaseTest { public static int value = 0; public synchronized int increment() { return value++; } } 

Is increment() method thread safe? Should I add the volatile keyword as follows:

  public static volatile int value = 0; 
+6
source share
4 answers

This code is not thread safe. The instance method will be synchronized in the instance, if you have multiple instances, they will not use the same monitor, and therefore updates can be interleaved.

You either need to remove the statics from the value field, or add a static method to the increment() method.

In addition, since you created the value public, there is an additional problem, the value can be changed or read outside of this method without using synchronization, which can lead to reading old values.

Thus, changing your code to the following will make it thread safe:

 public class IncreaseTest { private int value = 0; public synchronized int increment() { return value++; } } 
+18
source

I don’t think it’s thread safe, since the static variable is publicly accessible and other threads can be accessed in a safe manner. To be thread safe, you must declare a variable as follows:

 public static volatile int value; 

Now value , which is volatile, will be available in the synchronized block.

+1
source

If you use this method in two threads, you will need the volatile keyword. Without it, another thread may not receive the most recent value. (WITH#)

0
source

You should probably use atomicvars

0
source

All Articles