View Javadoc

1   /*
2    * $Id: RoundRobin.java 22146 2011-06-08 07:40:29Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.routing;
12  
13  import org.mule.api.MessagingException;
14  import org.mule.api.MuleEvent;
15  import org.mule.api.MuleException;
16  import org.mule.api.MuleMessage;
17  import org.mule.api.processor.MessageProcessor;
18  import org.mule.api.routing.CouldNotRouteOutboundMessageException;
19  import org.mule.api.routing.RoutingException;
20  import org.mule.routing.outbound.AbstractOutboundRouter;
21  
22  import java.util.concurrent.atomic.AtomicInteger;
23  
24  /**
25   * RoundRobin divides the messages it receives among its target routes in round-robin
26   * fashion. This includes messages received on all threads, so there is no guarantee
27   * that messages received from a splitter are sent to consecutively numbered targets.
28   */
29  public class RoundRobin extends AbstractOutboundRouter
30  {
31      /** Index of target route to use */
32      AtomicInteger index = new AtomicInteger(0);
33  
34      /**
35       *  Process the event using the next target route in sequence
36       */
37      @Override
38      public MuleEvent route(MuleEvent event) throws MessagingException
39      {
40          int modulo = getAndIncrementModuloN(routes.size());
41          if (modulo < 0)
42          {
43              throw new CouldNotRouteOutboundMessageException(event, this);
44          }
45          
46          MessageProcessor mp = routes.get(modulo);
47          try
48          {
49              return mp.process(event);
50          }
51          catch (MuleException ex)
52          {
53              throw new RoutingException(event, this, ex);
54          }
55      }
56  
57      /**
58       * Get the index of the processor to use
59       */
60      private int getAndIncrementModuloN(int modulus)
61      {
62          if (modulus == 0)
63          {
64              return -1;
65          }
66          while (true)
67          {
68              int lastIndex = index.get();
69              int nextIndex = (lastIndex + 1) % modulus;
70              if (index.compareAndSet(lastIndex, nextIndex))
71              {
72                  return nextIndex;
73              }
74          }
75      }
76  
77      @Override
78      public boolean isMatch(MuleMessage message) throws MuleException
79      {
80          return true;
81      }
82  }