Java - Happens before - volatile

Dhana Krishnasamy

I have the below code

class VolatileCount {
    volatile int count;
    Object lock = new Object();

    public void increment() {

        synchronized (lock) {
            count = count + 1;
        }
        System.out.print(" " + count);
    }

}

If I call increment() on same object from multiple threads I get the below output (might be different on your machine)

2 3 2 5 4 8 8 6 11 13 10 9 15 14 12 20 19

Looking at the repeating numbers I think happens-before seems to be broken, because considering first three number (2 3 2), if a thread sees 3 , increment has happened and since the variable is volatile, its value should be 3 or more but cannot be 2 in any thread.
However, the print line seems to have been reordered here, is it correct to reorder that line? What am I missing here? I run on JDK 7 (Eclipse)

dcastro

Update

Because you seem to want an explanation for the specific case of "2 3 2"

  • X increments i (now 1)
  • Y increments i (now 2)
  • X reads i (X loads 2)
  • Y reads i (Y loads 2)
  • Y prints the value previously loaded (prints 2)
  • Z increments i, reads i, prints i (prints 3)
  • X prints the value previously loaded (prints 2)

The point is: System.out.print(" " + count) isn't atomic. The thread can be preempted after performing a volatile read and before printing the value.

If you want to prevent duplicate values from being printed, you have to perform the volatile read inside the lock:

public void increment() {
    int localCount;
    synchronized (lock) {
        count = count + 1;
        localCount = count; // volatile load
    }
    System.out.print(" " + localCount);
}

This wouldn't prevent values from being printed out of order though. In order to print them in order, without duplicates, you'd have to move the print into the lock as well.

Old Answer

The print statement is outside the lock. Consider the code running inside System.out.print(" " + count).

  • A thread X increments i
  • Thread X evaluates the print arguments and performs a volatile read on the count variable, and loads the value 2.
  • Thread X is preempted by Thread Y, which increments i
  • Thread Y loads i (which is now 3), calls the print method which runs to completion.
  • Thread Y is preempted, and Thread X now runs print to completion, which prints 2.

This would make the numbers show out of order, such as "3 2 4".

Some numbers might also be repeated when:

  • Thread X increments i (which is now 2)
  • Thread Y increments i(which is now 3)
  • Thread X prints i (which is 3)
  • Thread Y prints i (which is 3)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

java - synchronization and volatile variable

From Java

Java happens-before relationship invokeAndWait

From Dev

Java Happens-Before and Thread Safety

From Dev

Java volatile and cache coherence

From Java

An equivalent to Java volatile in Python

From Dev

"Partial Ordering" and Happens-before relation java

From Dev

Java - Happens before - volatile

From Dev

Java - happens-before relationship for monitor unlock

From Dev

Java - is volatile required with synchronized?

From Dev

End of constructor as happens - before relation in Java

From Dev

append() happens before hide()

From Dev

Java Volatile Variable

From Dev

Happens-before mechanism in Java

From Dev

java volatile objects in non volatile objects

From Dev

java concurrency happens before

From Dev

Java Callable : What happens to the thread before get() is called

From Dev

Java memory model: volatile variables and happens-before

From Dev

Happens before and program order in Java Memory Model

From Dev

java Volatile/synchronization on arraylist

From Dev

Does a Java Lock object enforce a happens-before relationship?

From Dev

Java happens-before consistent thread view on two ConcurrentMaps

From Dev

Java : Licensing a webapp. Check for license before login happens

From Dev

Java Memory Model happens-before guarantees for Thread Pool interactions

From Dev

does volatile gives other normal stores and loads a happens-before relation?

From Dev

Why the volatile Happens-Before order for Instruction Reordering fails?

From Dev

Happens-before rules in Java Memory Model

From Dev

Java Memory Model happens-before guarantees for Thread Pool interactions

From Dev

"Happens-before" Java relate to volatile fields clarifiacation

From Dev

End of constructor as happens - before relation in Java

Related Related

  1. 1

    java - synchronization and volatile variable

  2. 2

    Java happens-before relationship invokeAndWait

  3. 3

    Java Happens-Before and Thread Safety

  4. 4

    Java volatile and cache coherence

  5. 5

    An equivalent to Java volatile in Python

  6. 6

    "Partial Ordering" and Happens-before relation java

  7. 7

    Java - Happens before - volatile

  8. 8

    Java - happens-before relationship for monitor unlock

  9. 9

    Java - is volatile required with synchronized?

  10. 10

    End of constructor as happens - before relation in Java

  11. 11

    append() happens before hide()

  12. 12

    Java Volatile Variable

  13. 13

    Happens-before mechanism in Java

  14. 14

    java volatile objects in non volatile objects

  15. 15

    java concurrency happens before

  16. 16

    Java Callable : What happens to the thread before get() is called

  17. 17

    Java memory model: volatile variables and happens-before

  18. 18

    Happens before and program order in Java Memory Model

  19. 19

    java Volatile/synchronization on arraylist

  20. 20

    Does a Java Lock object enforce a happens-before relationship?

  21. 21

    Java happens-before consistent thread view on two ConcurrentMaps

  22. 22

    Java : Licensing a webapp. Check for license before login happens

  23. 23

    Java Memory Model happens-before guarantees for Thread Pool interactions

  24. 24

    does volatile gives other normal stores and loads a happens-before relation?

  25. 25

    Why the volatile Happens-Before order for Instruction Reordering fails?

  26. 26

    Happens-before rules in Java Memory Model

  27. 27

    Java Memory Model happens-before guarantees for Thread Pool interactions

  28. 28

    "Happens-before" Java relate to volatile fields clarifiacation

  29. 29

    End of constructor as happens - before relation in Java

HotTag

Archive