[concurrency-interest] What can an incorrectly synchronized read see?

jingguo yao yaojingguo at gmail.com
Wed Sep 28 03:23:39 EDT 2016


Java code:

class Counter {
  private int val = 0;
  public synchronized int synchronizedGet() {
    return val;
  }
  public int unsynchronizedGet() {
    return val;
  }
  public synchronized void increment() {
    val++;
  }
}
class Writer extends Thread {
  private Counter c;
  public Writer(Counter c) {
    this.c = c;
  }
  @Override
  public void run() {
    c.increment();
  }
}
class Reader extends Thread {
  private Counter c;
  public Reader(Counter c) {
    this.c = c;
  }
  @Override
  public void run() {
    int unsynchronizedCount = c.unsynchronizedGet();
    int synchronizedCount = c.synchronizedGet();
    if (unsynchronizedCount > synchronizedCount)
      throw new RuntimeException("unsynchronized count is larger than
synchronized count");
  }
}
public class UnsynchronizedRead {
  public static void main(String[] args) {
    Counter c = new Counter();
    Writer w = new Writer(c);
    Reader r = new Reader(c);
    w.start();
    r.start();
  }
}


I think that unsynchronizedCount <= synchronizedCount is always true
for the above code provided that JVM implementations of read and write
operations for int type are atomic. Here is my reasoning.

When increment happens-before synchronizedGet, synchronizedGet sees 1.
And there is no happens-before order to prevent unsynchronizedGet from
seeing initial_write or increment. So unsynchronizedGet sees1 0 or 1.

Happens-before digram for this case:

  initial_write ---> increment ---> synchronizedGet
                                      ^
              unsynchronizedGet------/

When synchronizedGet happens-before increment, synchronizedGet sees 0. Since
unsynchronizedGet happens-before increment, it can't see 1 written
by increment. It can only see 0 written by initial_write.

Happens-before digram for this case:

  initial_write ---> synchronizedGet ---> increment
                        ^
  unsynchronizedGet----/

Is my reasoning correct?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20160928/4ed5e090/attachment.html>


More information about the Concurrency-interest mailing list