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?
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.
Unlike local variables, static fields and methods are NOT thread safe in Java.
Static variables in swift are not thread-safe by default.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With