1   package org.daisy.pipeline.tts;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   import java.util.List;
6   
7   public class RoundRobinLoadBalancer implements LoadBalancer {
8   	private int mIndex = 0;
9   	private Object mSyncPoint;
10  
11  	private List<Host> mHosts;
12  
13  	/**
14  	 * @param hostlist is the list of hosts. The first host will be considered
15  	 *            as the master host.
16  	 * @param syncPoint is used for locking when several threads attempt to call
17  	 *            selectHost() with the same syncPoint.
18  	 */
19  	public RoundRobinLoadBalancer(String hostlist, Object syncPoint) {
20  		mSyncPoint = syncPoint;
21  		String[] parts = hostlist.split("[ ,;\t\n]+");
22  		mHosts = new ArrayList<Host>();
23  
24  		for (int i = 0; i < parts.length; ++i) {
25  			try {
26  				Host h = new Host();
27  				String[] pair = parts[i].split(":");
28  				h.address = pair[0];
29  				h.port = Integer.valueOf(pair[1]);
30  				mHosts.add(h);
31  			} catch (Exception e) {
32  				throw new IllegalArgumentException("bad format for: '" + parts[i] + "'");
33  			}
34  		}
35  
36  	}
37  
38  	@Override
39  	public Host selectHost() {
40  		int index;
41  		if (mSyncPoint != null) {
42  			synchronized (mSyncPoint) {
43  				mIndex = (mIndex + 1) % mHosts.size();
44  				index = mIndex;
45  			}
46  		} else {
47  			mIndex = (mIndex + 1) % mHosts.size();
48  			index = mIndex;
49  		}
50  
51  		return mHosts.get(index);
52  	}
53  
54  	@Override
55  	public Collection<Host> getAllHosts() {
56  		return mHosts;
57  	}
58  
59  	@Override
60  	public Host getMaster() {
61  		return mHosts.get(0);
62  	}
63  
64  	@Override
65  	public void discard(Host h) {
66  		mHosts.remove(h);
67  	}
68  
69  	public void discardAll(Collection<Host> hosts) {
70  		mHosts.removeAll(hosts);
71  	}
72  
73  }