Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the following incrementation code thread safe in 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;
like image 933
codeisee Avatar asked Mar 02 '13 12:03

codeisee


People also ask

Is ++ thread-safe in Java?

Example of Non-Thread-Safe Code in Java The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.

How do I know if a code is thread-safe?

How do we know if code is thread-safe? We can tell that code is thread-safe if it only uses and updates shared resources in a way that guarantees safe execution by multiple threads at the same time. Shared resources can be a counter variable, an array, or anything else.

Which one is thread-safe in Java?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Is the ++ operator thread-safe?

The increment Java operator (++) is not thread-safe.


2 Answers

This code is not thread-safe. The instance method will synchronize on an instance, if you have multiple instances they will not use the same monitor and therefor the updates can interleave.

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

Also, as you have made value public, there is the additional problem that value can be changed or read outside of this method without using synchronisation which could result in reading old values.

So changing your code to the following will make it thread-safe:

public class IncreaseTest {
    private int value = 0;

    public synchronized int increment() {
        return value++;
    }
}
like image 111
Mark Rotteveel Avatar answered Sep 19 '22 06:09

Mark Rotteveel


You should probably use atomicvars

like image 25
Avner Levy Avatar answered Sep 20 '22 06:09

Avner Levy