01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */
19:
20: package org.apache.synapse.endpoints.algorithms;
21:
22: import org.apache.synapse.MessageContext;
23: import org.apache.synapse.endpoints.Endpoint;
24:
25: import java.util.ArrayList;
26:
27: /**
28: * This is the implementation of the round robin load balancing algorithm. It simply iterates through
29: * the endpoint list one by one for until an active endpoint is found.
30: */
31: public class RoundRobin implements LoadbalanceAlgorithm {
32:
33: private ArrayList endpoints = null;
34:
35: public RoundRobin(ArrayList endpoints) {
36: this .endpoints = endpoints;
37: }
38:
39: /**
40: * Choose an active endpoint using the round robin algorithm. If there are no active endpoints
41: * available, returns null.
42: *
43: * @param synapseMessageContext MessageContext instance which holds all per-message properties
44: * @return endpoint to send the next message
45: */
46: public Endpoint getNextEndpoint(
47: MessageContext synapseMessageContext,
48: AlgorithmContext algorithmContext) {
49:
50: Endpoint nextEndpoint;
51: int attempts = 0;
52: int currentEPR = algorithmContext.getCurrentEndpointIndex();
53: do {
54: // two successive clients could get the same endpoint if not synchronized.
55: synchronized (this ) {
56: nextEndpoint = (Endpoint) endpoints.get(currentEPR);
57:
58: if (currentEPR == endpoints.size() - 1) {
59: currentEPR = 0;
60: } else {
61: currentEPR++;
62: }
63: algorithmContext.setCurrentEPR(currentEPR);
64: }
65:
66: attempts++;
67: if (attempts > endpoints.size()) {
68: return null;
69: }
70:
71: } while (!nextEndpoint.isActive(synapseMessageContext));
72:
73: return nextEndpoint;
74: }
75:
76: public void reset(AlgorithmContext algorithmContext) {
77: algorithmContext.setCurrentEPR(0);
78: }
79: }
|