Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety in Java class

Why is this java class not Thread safe.

class TestClass {  
   private int x;

   int get() {
       return x;
   }

   void set(int x) {
       this.x = x;
   }  
}

I read that keyword synchronized is needed to make it thread safe? After all isn't the operations done inside atomic?

like image 658
softwarematter Avatar asked Aug 30 '10 16:08

softwarematter


People also ask

How do I make my class thread-safe?

To make these classes thread-safe, you must prevent concurrent access to the internal state of an instance by more than one thread. Because Java was designed with threads in mind, the language provides the synchronized modifier, which does just that.

Are Java class variables thread-safe?

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.

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

To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.

What does it mean for a class to be thread-safe?

Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously. Conditionally safe: Different threads can access different objects simultaneously, and access to shared data is protected from race conditions.


2 Answers

Although the assignment itself is an atomic operation, due to different hardware and compiler implementations, different threads may see different values of the member x. I.e., a modification by one thread may be invisible to the other thread, because of some kind of caching. This is usually called a thread visibility problem.

You can synchronize your code properly either by synchronizing on a monitor (using the synchronized keyword or the java.util.concurrent locks), or by declaring x to be volatile.

like image 123
Eyal Schneider Avatar answered Oct 19 '22 16:10

Eyal Schneider


With multiple processors, some values may be cached by the processor and may not reflect the changes made by other threads/processors for the same objects. Actually, JVM may be implemented to work this way even with a single processor.

Synchronized methods are explicitly required by language specification to present a memory barrier and require reread of all instance variables from the memory.

Because your code is not synchronized, one thread may set the value, but the other thread will return the value still cached by that thread.

Please read 'Memory and Locks' chapter of Java Language Specification.

like image 34
Alexander Pogrebnyak Avatar answered Oct 19 '22 17:10

Alexander Pogrebnyak