Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety for static variables

class ABC implements Runnable {
    private static int a;
    private static int b;
    public void run() {
    }
}

I have a Java class as above. I have multiple threads of this class. In the run() method, the variables a & b are incremented each for several times. On each increment, I am putting these variables in a Hashtable.

Hence, each thread will increment both variables and putting them in Hashtable. How can I make these operations thread safe?

like image 528
hoshang.varshney Avatar asked Sep 16 '11 09:09

hoshang.varshney


People also ask

Do threads share static variables?

Static variables are indeed shared between threads, but the changes made in one thread may not be visible to another thread immediately, making it seem like there are two copies of the variable.

Is static field thread safe in Java?

Unlike local variables, static fields and methods are NOT thread safe in Java.

Are static variables thread safe Swift?

Static variables in swift are not thread-safe by default.


2 Answers

I would use AtomicInteger, which is designed to be thread-safe and is dead easy to use and imparts the absolute minimal of synchronization overhead to the application:

class ABC implements Runnable {
    private static AtomicInteger a;
    private static AtomicInteger b;
    public void run() {
        // effectively a++, but no need for explicit synchronization!
        a.incrementAndGet(); 
    }
}

// In some other thread:

int i = ABC.a.intValue(); // thread-safe without explicit synchronization
like image 131
Bohemian Avatar answered Sep 30 '22 10:09

Bohemian


Depends on what needs to be thread-safe. For these int primitives, you'll need either to replace them with AtomicInteger's or only operate with them within synchronized method or block. If you need to make your cross-thread Hashtable thread-safe, you don't need to do anything, as it already is synchronized.

like image 26
Alex Abdugafarov Avatar answered Sep 30 '22 10:09

Alex Abdugafarov