我有一个从Disruptor eventHandler调用的同步方法prepareLog()。我正在调用在破坏者上发布的cacheInfo(),而后者又从eventHandler内部调用prepareLog()。当将prepareLog()声明为已同步时,中断事件处理程序并不总是被调用。但是,当prepareLog()未声明为已同步时,总是调用事件处理程序。
我不明白,为什么会这样。
以下是代码:
public static void main() {
Xyz xyzObject = new XyzObject();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<100; i++) {
xyzObject.cacheInfo("++++ %s) hello world ", i);
}
}
}).start();
}
Class XYZ {
public XYZ() {
ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE;
WaitStrategy waitStrategy = new BusySpinWaitStrategy();
Disruptor<Cacheda> disruptor
= new Disruptor<>(
Cacheda.EVENT_FACTORY,
32,
threadFactory,
ProducerType.SINGLE,
waitStrategy);
disruptor.handleEventsWith(getEventHandler());
mRingBuffer = disruptor.start();
}
private synchronized void cacheInfo(String message, Object... args) {
long sequenceID = mRingBuffer.next();
Cacheda data = mRingBuffer.get(sequenceID);
data.setMessage(message);
data.setArguments(args);
mRingBuffer.publish(sequenceID);
}
// doesn't always get called IF prepareLog() is declared SYNCHRONIZED
private EventHandler<Cacheda >[] getEventHandler() {
System.out.println("getEventHandler()");
EventHandler<Cacheda> eventHandler = new EventHandler<Cacheda>() {
@Override
public void onEvent(Cacheda data, long sequence, boolean endOfBatch) throws Exception {
prepareLog(data);
}
};
return new EventHandler[] {eventHandler};
}
private synchronized void prepareLog(final Cacheda cached) {
System.out.println("Thread id: "+ Thread.currentThread().getName());
//lots of logic in here.
}
}