Search code examples
javaevent-handlingdisruptor-pattern

Disruptor: setting EventHandler order


I am a newbie to disruptor and I am using disruptor for passing between threads in a pipeline-like structure.I can run a set of handlers as below with hadleEventsWith or using after().

disruptor.handleEventsWith(eventhandler1)
                .then(eventhandler2)
                .then(eventhandler3);

But,I want to be able to add new EventHandlers to this pipeline without changing the code here.To do this, I am adding an integer value to each event handler.Then,I am taking those values and the relevant handlers to create an ordered list of handlers. Then, to give the ordering to disruptor what I am currently doing is

disruptor.handleEventsWith(handlerOrderList.get(0));
for (int i=1; i<handlerOrderList.size();i++) {
     disruptor.after(handlerOrderList.get(i1)).then(handlerOrderList.get(i));
 }

Is there any better way of doing this?


Solution

  • Something like this might be much more readable:

        EventHandler<YourTypeHere>[] handlers = getOrderedHandlersAsArray();
        disruptor.handleEventsWith(handlers);
    

    UPDATE: You are right. In the above case, the handlers will process the events in parallel. To process the events sequentially, you might try something like the following :

        EventHandlerGroup<T> eventHandlerGroup = null;
        for (T handler : handlers) {
            if (eventHandlerGroup == null) {
                eventHandlerGroup = disruptor.handleEventsWith(handler);
            } else {
                eventHandlerGroup.then(handler);
            }
        }