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