At-most-once execution


Series Overview

This article is part of the series. Below are links to all posts in the series:
  1. At-Most-Once Execution
  2. Mastering Read-Write Lock

What's inside this article ⌄
  • Java double checked locking pattern
  • Synchronized block optimization
  • Volatile boolean thread safety
  • Critical section performance Java
  • Execute critical section at most once
  • At-most-once execution

Suppose you have a critical section, which is being called by a bunch of threads simultaneously:

synchronized (mutex) {
    System.out.println("heavy computations");
    Thread.sleep(2000);
}

It quickly becomes a bottleneck: every thread will be blocked in a waiting-for-the-lock state. However, there is room for minimizing synchronization overhead if you can afford at-most-one code execution.

Meaning that other threads may skip this code execution in case it is already running. All we need to do is impose double-checked locking:

private volatile boolean isExecuting = false;

public void executeCode() {
    if (!isExecuting) {
        synchronized (this) {
            if (!isExecuting) {
                isExecuting = true;
                try {
                    // Your code that should be executed at most once
                } finally {
                    isExecuting = false;
                }
            }
        }
    }
}

Basically, that’s all. Your program will definitely work much faster.

An important thing to consider here is that, in some cases, you may want to run this section again at the end of the algorithm.

Therefore, all you need to do is impose another boolean flag like force and place it accordingly nearby with isExecuting.

Happy synchronizing!