Balking Pattern - Implementation

Implementation

Below is a general, simple example for an implementation of the balking pattern as originally seen in Grand (2002). As demonstrated by the definition above, notice how the "synchronized" line is utilized. If there are multiple calls to the job method, only one will proceed while the other calls will return with nothing. Another thing to note is the jobCompleted method. The reason it is synchronized is because the only way to guarantee another thread will see a change to a field is to synchronize access all access to it or declare it as volatile.

public class Example { private boolean jobInProgress = false; public void job { synchronized(this) { if (jobInProgress) { return; } jobInProgress = true; } // Code to execute job goes here // ... } void jobCompleted { synchronized(this) { jobInProgress = false; } } }

Read more about this topic:  Balking Pattern