1 /* 2 * #%L 3 * LatencyServerSelector.java - mongodb-async-driver - Allanbank Consulting, Inc. 4 * %% 5 * Copyright (C) 2011 - 2014 Allanbank Consulting, Inc. 6 * %% 7 * Licensed under the Apache License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. 9 * You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software 14 * distributed under the License is distributed on an "AS IS" BASIS, 15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 * See the License for the specific language governing permissions and 17 * limitations under the License. 18 * #L% 19 */ 20 package com.allanbank.mongodb.client.state; 21 22 import java.util.ArrayList; 23 import java.util.Collections; 24 import java.util.List; 25 26 /** 27 * LatencyServerSelector provides an implementation of the server selector that 28 * uses the server latencies to determine the server to select. 29 * 30 * @api.no This class is <b>NOT</b> part of the drivers API. This class may be 31 * mutated in incompatible ways between any two releases of the driver. 32 * @copyright 2012-2013, Allanbank Consulting, Inc., All Rights Reserved 33 */ 34 public class LatencyServerSelector implements ServerSelector { 35 36 /** The cluster to choose from. */ 37 private final Cluster myCluster; 38 39 /** If true then only writable servers should be selected. */ 40 private final boolean myWritableOnly; 41 42 /** 43 * Creates a new LatencyServerSelector. 44 * 45 * @param cluster 46 * The cluster to choose from. 47 * @param writableOnly 48 * If true then only writable servers should be selected. If 49 * false then any server (writable and not writable) may be 50 * selected. 51 */ 52 public LatencyServerSelector(final Cluster cluster, 53 final boolean writableOnly) { 54 myCluster = cluster; 55 myWritableOnly = writableOnly; 56 } 57 58 /** 59 * {@inheritDoc} 60 * <p> 61 * Overridden to order the servers with the lowest latency first. 62 * </p> 63 */ 64 @Override 65 public List<Server> pickServers() { 66 List<Server> servers; 67 if (myWritableOnly) { 68 servers = myCluster.getWritableServers(); 69 } 70 else { 71 servers = myCluster.getServers(); 72 } 73 74 // If there are no servers then there is no one to pick. 75 if (servers.isEmpty()) { 76 return Collections.emptyList(); 77 } 78 79 // Copy to a list we know we can modify and sort. 80 servers = new ArrayList<Server>(servers); 81 Collections.sort(servers, ServerLatencyComparator.COMPARATOR); 82 83 return servers; 84 } 85 }