Google guava の、Release 10 が公開されてる。
http://code.google.com/p/guava-libraries/
com.google.common.eventbus というこんなのがあったらいいなというpackage が追加されてる。
Subscribeアノテーションを付けたメソッドに任意のObjectをイベント通知できる。
簡単なサンプル
import com.google.common.eventbus.Subscribe;
//
public class SubProcess implements Runnable{
private int count = 0;
@Override
public void run(){
System.out.println("run() START");
while(this.count > 3){
}
System.out.println("run() END");
}
@Subscribe
public void onMessage(String message){
this.count++;
System.out.println("message = "+message+" count = "+this.count);
}
}
これを、EventBus で通知する場合と AsyncEventBus で通知する場合、を比べてみると、、
Runnable process = new SubProcess();
ExecutorService service = Executors.newSingleThreadExecutor();
EventBus bus = new EventBus();
bus.register(process);
bus.post("EventBus test 1");
service.submit(process);
bus.post("EventBus test 2");
bus.post("EventBus test 3");
service.shutdown();
// AsyncEventBus は、Executor を指定
Runnable aprocess = new SubProcess();
ExecutorService aservice = Executors.newSingleThreadExecutor();
AsyncEventBus abus = new AsyncEventBus(aservice);
abus.register(aprocess);
abus.post("AsyncEventBus test 1");
aservice.submit(aprocess);
abus.post("AsyncEventBus test 2");
abus.post("AsyncEventBus test 3");
aservice.shutdown();
結果は以下のように、AsyncEventBus 使用時は、submit 実行のタイミングで、
通知されないイベントが発生する。
---------------------
message = EventBus test 1 count = 1
run() START
message = EventBus test 2 count = 2
message = EventBus test 3 count = 3
run() END
message = AsyncEventBus test 1 count = 1
run() START
---------------------
もっとサンプルらしいものは、以下が、Cool!
http://insightfullogic.com/blog/2011/oct/10/eventbus/