Система событий

This commit is contained in:
Gravit 2018-10-18 20:25:57 +07:00
parent e5d3dd9a03
commit 5c99ffd69a
No known key found for this signature in database
GPG key ID: 061981E1E85D3216
3 changed files with 83 additions and 0 deletions

View file

@ -0,0 +1,6 @@
package ru.gravit.utils.event;
@FunctionalInterface
public interface EventHandler {
void run(EventInterface event);
}

View file

@ -0,0 +1,7 @@
package ru.gravit.utils.event;
import java.util.UUID;
public interface EventInterface {
UUID getUUID();
}

View file

@ -0,0 +1,70 @@
package ru.gravit.utils.event;
import ru.gravit.utils.helper.LogHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class EventManager {
public static final int QUEUE_MAX_SIZE = 2048;
public static final int INITIAL_HANDLERS_SIZE = 16;
public class Entry
{
public Entry(EventHandler func, UUID[] events) {
this.func = func;
this.events = events;
}
EventHandler func;
UUID[] events;
}
public class QueueEntry
{
public QueueEntry(EventInterface event, UUID key) {
this.event = event;
this.key = key;
}
EventInterface event;
UUID key;
}
public ArrayList<Entry> handlers = new ArrayList<>(INITIAL_HANDLERS_SIZE);
public BlockingQueue<QueueEntry> queue = new LinkedBlockingQueue<>(QUEUE_MAX_SIZE); //Максимальный размер очереди
public int registerHandler(EventHandler func, UUID[] events)
{
Arrays.sort(events);
handlers.add(new Entry(func,events));
return handlers.size();
}
public void sendEvent(UUID key, EventInterface event, boolean blocking)
{
if(blocking) process(key,event);
else queue.add(new QueueEntry(event,key));
}
public void process(UUID key, EventInterface event)
{
for(Entry e : handlers)
{
if(Arrays.binarySearch(e.events,key) >= 0) e.func.run(event);
}
}
public class EventExecutor implements Runnable {
public boolean enable = true;
@Override
public void run() {
while(enable && !Thread.interrupted())
{
try {
QueueEntry e = queue.take();
process(e.key,e.event);
} catch (InterruptedException e) {
LogHelper.error(e);
}
Thread.yield();
}
}
}
}