All Downloads are FREE. Search and download functionalities are using the official Maven repository.

netflix.ocelli.loadbalancer.RoundRobinLoadBalancer Maven / Gradle / Ivy

package netflix.ocelli.loadbalancer;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import netflix.ocelli.LoadBalancer;
import rx.Subscriber;

/**
 * Very simple LoadBlancer that when subscribed to gets an ImmutableList of active clients 
 * and round robins on the elements in that list
 * 
 * @author elandau
 *
 * @param 
 */
public class RoundRobinLoadBalancer extends LoadBalancer {
    public static  RoundRobinLoadBalancer create() {
        return create(-1);
    }
    
    public static  RoundRobinLoadBalancer create(int seedPosition) {
        return new RoundRobinLoadBalancer(seedPosition);
    }

    private final AtomicReference> clients;
    
    RoundRobinLoadBalancer(int seedPosition) {
        this(new AtomicInteger(seedPosition), new AtomicReference>(new ArrayList()));
    }

    private RoundRobinLoadBalancer(final AtomicInteger position, final AtomicReference> clients) {
        super(new OnSubscribe() {
            @Override
            public void call(final Subscriber s) {
                List local = clients.get();
                if (local.isEmpty()) {
                    s.onError(new NoSuchElementException("No servers available in the load balancer"));
                }
                else {
                    int pos = position.incrementAndGet();
                    while (pos < 0) {
                        if (position.compareAndSet(pos, 0)) {
                            pos = 0;
                            break;
                        }
                        pos = position.incrementAndGet();
                    }
                    s.onNext(local.get(pos % local.size()));
                    s.onCompleted();
                }
            }
        });
        
        this.clients = clients;
    }
    
    @Override
    public void call(List t) {
        this.clients.set(t);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy