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, blockingHandle handle = handleSet.select();// promote new leaderpromoteNewLeader();// process handlhandleSet.handle(handle);// reenter to next loop}}private void waitToLeader() {synchronized (monitor) {try {monitor.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void promoteNewLeader() {synchronized (monitor) {monitor.notify();}}class WorkThread extends Thread {ThreadPool tp;public WorkThread(ThreadPool tp) {this.tp = tp;}@Overridepublic 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