10

Consider the snippet from Java Concurrency in Practice-

@ThreadSafe
public class SynchronizedInteger{
    @GuardedBy("this") private int value;

    public synchronized int getValue() {
        return value;
    }

    public synchronized void setValue(int value) {
        this.value = value;
    }
}

An extract from the same book-

A good way to think about volatile variables is to imagine that they behave roughly like the SynchronizedInteger class in Listing above, replacing reads and writes of the volatile variable with calls to get and set. Yet accessing a volatile variable performs no locking and so cannot cause the executing thread to block, making volatile variables a lighter-weight synchronization mechanism than synchronized.

A special case of thread confinement applies to volatile variables. It is safe to perform read-modify-write operations on shared volatile variables as long as you ensure that the volatile variable is only written from a single thread.

So, if you make the instance variable in the above class as volatile and then remove the synchronized keyword, after that suppose there are 3 threads

Thread A & Thread B are writing to the same volatile variable.
Thread C reads the volatile variable.

Since the volatile variable is now written from 2 threads, why is it unsafe to perform read-modify-write operations on this shared volatile variable?

4 Answers 4

4

The keyword volatile is used to ensure that changes to your Object will be seen by other Threads. This does not enforce, that non-atomic operations on the Object will be performed without an other Thread interfering before the operation is finished. For enforcing this you will need the keyword synchronized.

3

It's because read-modify-write operations on volatile variables are not atomic. v++ is actually something like:

r1 = v;
r2 = r1 + 1;
v = r2;

So if you have two threads performing this operation once each, it could possibly result in the variable being incremented only once, as they both read the old value. That's an example of why it's not safe.

In your example it would be not safe if you removed synchronized, made the field volatile and had two threads calling setValue after some conditional logic based on the return of getValue - the value could have been modified by the other thread.

If you want atomic operations look at the java.util.concurrent.atomic package.

1

If you write volatile variable from multiple threads without using any synchronized constructs, you are bound to get data inconsistency errors.

Use volatile variables without synchronization in case of single write thread and multiple read threads for atomic operations.

Volatile make sure that variable value is fetched from main memory instead of Thread cache. It's safe to use in case of single write and multiple read operations.

Use Atomic variables or synchronization or Lock API to update and read variables from multiple threads.

Refer to related SE question:

What is meant by "thread-safe" code?

1

If two threads are writing without reading the variable first, there is no problem.. it is safe. Problem arises if a thread first reads, then modifies and then writes. What if second thread is also reading at the same time, reads the same old value as the first thread, and modifies it.. and when it writes, it will simply overwrite the first threads update. BOOM.

val i = 1 -> Thread reads 1 -> Threads 2 reads 1 -> Thread 1 does 1 * .2 = 1.2 -> Thread 2 does 1 * .3 = 1.3 -> Thread 1 writes 1.2 back -> Thread 2 cooly overwrites it to 1.3 instead of doing 1.2 * .3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.