package
org.eredlab.g4.rif.pushlet.core; import
org.eredlab.g4.rif.pushlet.util.Log; /** *
Abstract Event source from which Events are pulled. * *
@author *
@since 2011-05-12 */ abstract public class EventPullSource implements EventSource, Runnable {
private volatile boolean alive = false;
private volatile boolean active = false;
private static int threadNum = 0;
private Thread thread;
public EventPullSource() {
}
abstract protected long getSleepTime();
abstract protected Event pullEvent();
public void start() {
thread = new Thread(this, "EventPullSource-" + (++threadNum));
thread.setDaemon(true);
thread.start();
}
public boolean isAlive() {
return alive;
}
/**
* Stop the event generator thread.
*/
public void stop() {
alive = false;
if (thread != null) {
thread.interrupt();
thread = null;
}
}
/**
* Activate the event generator thread.
*/
synchronized public void activate() {
if (active) {
return;
}
active = true;
if (!alive) {
start();
return;
}
Log.debug(getClass().getName() + ":
notifying...");
notifyAll();
}
/**
* Deactivate the event generator thread.
*/
public void passivate() {
if (!active) {
return;
}
active = false;
}
/**
* Main loop: sleep, generate event and publish.
*/
public void run() {
Log.debug(getClass().getName() + ":
starting...");
alive = true;
while (alive) {
try {
Thread.sleep(getSleepTime());
// Stopped during sleep: end loop.
if (!alive) {
break;
}
// If passivated wait until we get
// get notify()-ied. If there are no subscribers
// it wasts CPU to remain producing events...
synchronized (this) {
while (!active) {
Log.debug(getClass().getName() + ":
waiting...");
wait();
}
}
} catch (InterruptedException
e) {
break;
}
try {
// Derived class should produce an event.
Event event = pullEvent();
// Let the publisher push it to subscribers.
Dispatcher.getInstance().multicast(event);
} catch (Throwable
t) {
Log.warn("EventPullSource exception while multicasting ",
t);
t.printStackTrace();
}
}
Log.debug(getClass().getName() + ":
stopped");
} }
EventPullSource源码分享
最新推荐文章于 2024-08-19 10:48:26 发布
本文介绍了一个事件推送源的抽象类实现,该类提供了一种从事件源中拉取事件的方法,支持线程管理、事件激活与停用,以及事件生成与发布的基本流程。
388

被折叠的 条评论
为什么被折叠?



