1
2
3
4
5
6
7
8
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
26
27
28
29 public class RoundRobin extends AbstractOutboundRouter
30 {
31
32 AtomicInteger index = new AtomicInteger(0);
33
34
35
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
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 }