I put together a simple example that sorta shows how ive been doing async event publications as of late. Check it out, I think its pretty self explanatory:
The main method:
public static void main(String[] args) throws InterruptedException {
Observer obs = new Observer();
EventBus.subscribe(obs, SomeEventImp.class);
SomeEventImp evt = new SomeEventImp(new Object(), "This is the value");
EventBus.publishAsync(evt);
Thread.sleep(Long.MAX_VALUE);
}
The Observer interface:
public interface IObserver {
public void update(AEvent event);
}
And Observer implementation:
public class Observer implements IObserver {
@Override
public void update(AEvent event) {
System.out.println("I got and event from " + event.getSource() + " with a value of " + event.getValue());
}
}
The AEvent class:
public abstract class AEvent<T> {
protected final T value;
protected final Object source;
public AEvent(Object source, T value) {
this.value = value;
this.source = source;
}
public Object getSource() {
return source;
}
public T getValue() {
return value;
}
}
The event bus:
public class EventBus {
// our observers
private static HashMap<IObserver, Class<?>> m_Observers = new HashMap<IObserver, Class<?>>();
// our incoming events
private static BlockingQueue<AEvent<?>> incoming = new LinkedBlockingQueue<AEvent<?>>();
// start our internal thread
static {
new Thread(new DelegationThread()).start();
}
// subscribe an observer
public static void subscribe(IObserver obs, Class<?> evtClass) {
synchronized (m_Observers) {
m_Observers.put(obs, evtClass);
}
}
// publish and event
public static void publishAsync(AEvent<?> event) {
incoming.add(event);
}
private static class DelegationThread implements Runnable {
@Override
public void run() {
while (true) {
try {
AEvent<?> evnt = incoming.take();
synchronized (m_Observers) {
for (Entry<IObserver, Class<?>> entry : m_Observers.entrySet()) {
if (entry.getValue() == evnt.getClass()) {
entry.getKey().update(evnt);
}
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
and finally the event implementation:
public class SomeEventImp extends AEvent<String> {
public SomeEventImp(Object source, String value) {
super(source, value);
}
}
And heres the output:
I got and event from java.lang.Object@5e1387c6 with a value of This is the value
Clearly you would want to clean this up a bit... I did just sorta slap this together in a few minutes, and didnt really check it all that well.