32. Balking mode: Talking about the thread-safe singleton mode-concurrent design mode-to be completed

1. Scene

The automatic saving function provided by the editor needs to be quickly abandoned: the save operation is automatically performed after a certain time. If the file has not been modified, the save operation needs to be quickly abandoned.

class AutoSaveEditor {
	// 文件是否被修改过,这个变量没有同步,通过对其加锁来保证类的线程安全
	boolean changed = false;
	// 定时任务线程池
	ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

	// 定时执行自动保存
	void startAutoSave() {
		ses.scheduleWithFixedDelay(() -> {
			autoSave();
		}, 5, 5, TimeUnit.SECONDS);
	}

	// 文件自动存盘操作,读写changed加锁,减少加锁范围
	void autoSave() {
		synchronized(this){
			if (!changed) {
				return;
			}
			changed = false;
		}
		// 执行存盘操作
		// 省略且实现
		this.execSave();
	}

	// 编辑操作
	void	edit(){
		//省略编辑逻辑
		......
		// 读写changed加锁,减少加锁范围
		synchronized(this){
			changed	= true;
		}
	}
}

The shared variable is a state variable, which is essentially a multi-threaded version of if. Some people summarize it as the Balking mode.

2. The classic implementation of Balking mode

class AutoSaveEditor {
	// 文件是否被修改过,这个变量没有同步,通过对其加锁来保证类的线程安全
	boolean changed = false;
	// 定时任务线程池
	ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

	// 定时执行自动保存
	void startAutoSave() {
		ses.scheduleWithFixedDelay(() -> {
			autoSave();
		}, 5, 5, TimeUnit.SECONDS);
	}

	// 文件自动存盘操作,读写changed加锁,减少加锁范围
	void autoSave() {
		synchronized(this){
			if (!changed) {
				return;
			}
			changed = false;
		}
		// 执行存盘操作
		// 省略且实现
		this.execSave();
	}

	// 编辑操作
	void	edit(){
		//省略编辑逻辑
		......
		// 读写changed加锁,减少加锁范围
		change();
	}

	private void change() {
		synchronized(this){
			changed	= true;
		}
	}
}

Balking mode is essentially a solution to the "multi-threaded version of if" in a standardized way. For the example of automatic saving above, the writing method after using the Balking mode to normalize is shown below. The assignment operation of the shared variable changed is extracted into change (), which has the advantage of separating concurrent processing logic from business logic .

3. Balking mode with volatile

Published 97 original articles · praised 3 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_39530821/article/details/102848355