Leader/Follower模式的简单实现

Leader/Follower相比较于普通的ThreadPool的优点

1、无需context switch,减少了线程间数据copy

2、无需维护一个队列,占用而外的内存空间

 

lf模式理解起来稍微有些困难,所以写了一个小的事例程序帮助自己理解

 

public class ThreadPool {
	private final static Object monitor = new Object();
	private final static int THREAD_POO_SIZE = 5;

	private Reactor handleSet = new Reactor();

	public ThreadPool(Reactor handleSet) {
		this.handleSet = handleSet;
	}

	public void init() {
		for (int i = 0; i < THREAD_POO_SIZE; i++) {
			new WorkThread(this).start();
		}
		this.promoteNewLeader();
	}

	public void join() {
		for (;;) {
			waitToLeader();
			// select, blocking
			Handle handle = handleSet.select();

			// promote new leader
			promoteNewLeader();

			// process handl
			handleSet.handle(handle);

			// reenter to next loop
		}
	}

	private void waitToLeader() {
		synchronized (monitor) {
			try {
				monitor.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void promoteNewLeader() {
		synchronized (monitor) {
			monitor.notify();
		}
	}

	class WorkThread extends Thread {
		ThreadPool tp;

		public WorkThread(ThreadPool tp) {
			this.tp = tp;
		}

		@Override
		public void run() {
			tp.join();
		}

	}
}

 

在lf模式中,线程有3种状态


它们通过以下两个方法来实现切换:

waitToLeader

promoteNewLeader

利用了java线程间通信的特性, 实现leader/follower线程的切换

目前java实现线程间通信,有两种方法:

1、Object.wait, Object.notify

2、Condition.await, Condition.signal

 

另一个疑问,就是要在系统初始化好后,调用promoteNewLeader,提升一个线程作为leader thread,监听事件的到来。

 

lf thread pool改进点:

1、thread pool大小可调节,可以参考ThreadPoolExecutor的实现

2、更多通用化,抽取变化点

 

Leader/Follower 论文参考:

http://www.kircher-schwanninger.de/michael/publications/lf.pdf

http://www.cse.wustl.edu/~schmidt/PDF/reactor-siemens.pdf

http://www.cse.wustl.edu/~schmidt/PDF/proactor.pdf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值