Java Concurrency - Fine-grained synchronization

> Procedural Languages > Java > Java - Concurrency (Parallel Work)

1 - About

Synchronized statements are also useful for improving concurrency with fine-grained synchronization.

3 - Example

Suppose:

  • class MsLunch has two instance fields, c1 and c2,
  • c1 and c2 are never used together.
  • All updates of c1 and c2 must be synchronized,
  • There's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking.

Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

public class MsLunch {
 
    // two instance fields, c1 and c2
    private long c1 = 0;
    private long c2 = 0;
 
    // two objects solely to provide locks
    private Object lock1 = new Object();
    private Object lock2 = new Object();
 
    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }
 
    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}
Advertising