我的目标是按顺序发布异步事件,这些事件也按顺序到达并花费任意时间进行处理。所以下面是我目前仅使用wait
and的实现notify
。MyThread
处理事件,按 id 将结果放入哈希表,并Scheduler
在按顺序发布此事件之前通知线程是否被阻塞。
java.util.concurrent
使用包实现此功能的更好和更简洁的方法是什么?
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class AsyncHandler {
private final Map<Integer, Object> locks = new ConcurrentHashMap<Integer, Object>();
private final Map<Integer, Result> results = new ConcurrentHashMap<Integer, Result>();
private static final Random rand = new Random();
public AsyncHandler () {
new Scheduler(this, locks, results).start();
}
public void handleEvent(Event event) {
System.out.println("handleEvent(" + event.id + ")");
new MyThread(this, event, locks, results).start();
}
public Result processEvent (Event event) {
System.out.println("processEvent(" + event.id + ")");
locks.put(event.id, new Object());
try {
Thread.sleep(rand.nextInt(10000));
} catch (InterruptedException e) {
System.out.println(e);
}
return new Result(event.id);
}
public void postProcessEvent (Result result) {
System.out.println(result.id);
}
public static void main (String[] args) {
AsyncHandler async = new AsyncHandler();
for (int i = 0; i < 100; i++) {
async.handleEvent(new Event(i));
}
}
}
class Event {
int id;
public Event (int id) {
this.id = id;
}
}
class Result {
int id;
public Result (int id) {
this.id = id;
}
}
class MyThread extends Thread {
private final Event event;
private final Map<Integer, Object> locks;
private final Map<Integer, Result> results;
private final AsyncHandler async;
public MyThread (AsyncHandler async, Event event, Map<Integer, Object> locks, Map<Integer, Result> results) {
this.async = async;
this.event = event;
this.locks = locks;
this.results = results;
}
@Override
public void run () {
Result res = async.processEvent(event);
results.put(event.id, res);
Object lock = locks.get(event.id);
synchronized (lock) {
lock.notifyAll();
}
}
}
class Scheduler extends Thread {
private int curId = 0;
private final AsyncHandler async;
private final Map<Integer, Object> locks;
private final Map<Integer, Result> results;
public Scheduler (AsyncHandler async, Map<Integer, Object> locks, Map<Integer, Result> results) {
this.async = async;
this.locks = locks;
this.results = results;
}
@Override
public void run () {
while (true) {
Result res = results.get(curId);
if (res == null) {
Object lock = locks.get(curId);
//TODO: eliminate busy waiting
if (lock == null) {
continue;
}
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println(e);
System.exit(1);
}
}
res = results.get(curId);
}
async.postProcessEvent(res);
results.remove(curId);
locks.remove(curId);
curId++;
}
}
}