Skip to content

Instantly share code, notes, and snippets.

@voidc
Created April 23, 2015 18:07
Show Gist options
  • Save voidc/8fa46411d19ef2f7c8ee to your computer and use it in GitHub Desktop.
Save voidc/8fa46411d19ef2f7c8ee to your computer and use it in GitHub Desktop.
Java Event System
package event;
import java.util.HashMap;
import java.util.Map;
public class EventBus extends Thread {
private EventQueue eventQueue = new EventQueue(8);
private Map<Class<?>, EventListener<?>> listeners = new HashMap<>();
public EventBus() {
this.setDaemon(true);
}
@Override
public void run() {
while(true) {
update();
}
}
public synchronized void handle(Object event) {
eventQueue.push(event);
}
@SuppressWarnings("unchecked")
public void update() {
if(eventQueue.count() == 0) return;
Object event = eventQueue.next();
for(Class<?> eventType : listeners.keySet()) {
if(eventType.equals(event.getClass())) {
boolean consume = listeners.get(eventType).handle(eventType.cast(event));
if(consume) break;
}
}
}
public synchronized void register(Class<?> eventType, EventListener<?> listener) {
listeners.put(eventType, listener);
}
}
package event;
@FunctionalInterface
public interface EventListener<E> {
public boolean handle(E event);
}
package event;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EventQueue implements Iterator<Object>, Iterable<Object> {
private Object[] buffer;
private boolean overwrite;
private int tail = 0, head = 0;
public EventQueue(int bufferSize) {
this(bufferSize, true);
}
public EventQueue(int bufferSize, boolean overwrite) {
this.buffer = new Object[bufferSize];
this.overwrite = overwrite;
}
public void push(Object e) {
if(tail == buffer.length-1) {
if(!overwrite) throw new ArrayIndexOutOfBoundsException("buffer overflow");
head++;
}
buffer[tail++ % buffer.length] = e;
}
public Object peek() {
if(!hasNext()) throw new NoSuchElementException("buffer empty");
return buffer[head % buffer.length];
}
@Override
public Object next() {
if(!hasNext()) throw new NoSuchElementException("buffer empty");
return buffer[head++ % buffer.length];
}
public void skip(int n) {
head += Math.max(0, Math.min(n, count()));
}
public void clear() {
while(hasNext()) {
next();
}
}
public int count() {
return Math.abs(tail - head);
}
@Override
public boolean hasNext() {
return count() > 0;
}
@Override
public Iterator<Object> iterator() {
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment