У меня есть синхронизированный метод prepareLog (), который вызывается из EventHandler Disruptor.Я вызываю cacheInfo (), который публикует данные на разрушителе, который, в свою очередь, вызывает prepareLog () из EventHandler.Когда объявляется prepareLog () как синхронизированный, обработчик события disruptor не всегда вызывается.Однако, когда 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.
}
}