** balk ** means to stop and go home. Baseball balk is also balk. Similar to the Guarded Suspension pattern, the Balking pattern also has ** guard conditions **. In the Balking pattern, if the guard condition is not met, it will be interrupted immediately. This is different from the Guarded Suspension pattern, which waits until it is ready to run.
Think of something like the auto-save feature of an editor. There is a thread that periodically writes the contents of the current data to a file. Save only when the data content is updated. The guard condition is that there is a difference in the data contents, and if there is no difference, it returns (balk) without writing to the file.
(See this manual for the entire code)
...
public synchronized void change(String newContent) {
content = newContent;
changed = true;
}
public synchronized void save() throws IOException {
if (!changed) { //If not changed
return; //balk
}
doSave();
changed = false;
}
...
The GuardedObject role is a class that has a guarded method. If the guard condition is met, it will be executed immediately, and if it is not met, it will return without going to the actual processing. The GuardedObjec role may have a method (stateChangingMethod) that changes the state of the instance. In the sample program, the Data class plays this role, the save method corresponds to guardedMethod, and the change field corresponds to stateChangingMethod.
--When there is no need for processing --If you don't want to wait for the guard conditions to be met --If the guard condition is met only the first time. For example, if you want to check if it is initialized, and if it is not initialized, initialize it only once.
...
public synchronized void init() {
if (initialized) {
return;
}
doInit();
initialized = true;
}
A "variable whose state changes only once", such as an initialized field, is generally called a ** latch ** (latch).
As an intermediate between the Balking pattern and the Guarded Suspension pattern, there is a workaround that ** waits for a certain period of time until the guard condition is met **. The process of waiting for a certain period of time until the guard condition is satisfied and then balking when the condition is not satisfied is called ** guarded timed ** or ** timeout **.
obj.wait(1000) //Wait 1000ms
However, Java has no way to distinguish between ** notify / notifyAll and timed out **.
Relation Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 1) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 2) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 3) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 4) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 5)
Recommended Posts