Skip to content

Instantly share code, notes, and snippets.

@fwrq41251
Last active July 23, 2019 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwrq41251/e22784bd8a0a576cba6ccc097b1de2ee to your computer and use it in GitHub Desktop.
Save fwrq41251/e22784bd8a0a576cba6ccc097b1de2ee to your computer and use it in GitHub Desktop.
pool
package com.aemobile.pool;
/**
* Created by winry on 2019/7/19.
*/
public class SimpleConnection implements Connection {
private String server;
public SimpleConnection(String server) {
this.server = server;
}
public String getServer() {
return server;
}
@Override
public boolean isConnectionLost() {
return false;
}
}
package org.winry;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by winry on 2019/7/19.
*/
public class SimpleConnectionPool implements ConnectionPool {
private List<Connection> connections = new ArrayList<>();
private final Random rand = new Random();
public SimpleConnectionPool(String[] servers, int perServerConnectionCount) {
for (String server : servers) {
for (int i = 0; i < perServerConnectionCount; i++) {
Connection connection = new SimpleConnection(server);
connections.add(connection);
}
}
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
updateConnections();
}
}, 30, 30, TimeUnit.SECONDS);
}
@Override
public Connection getConnection() {
if (connections.isEmpty()) return null;
int index = rand.nextInt(connections.size());
for (int i = 0; i < connections.size(); i++) {
Connection connection = connections.get(index);
if (!connection.isConnectionLost()) {
return connection;
} else {
index++;
if (index >= connections.size()) index = 0;
}
}
return null;
}
private void updateConnections() {
boolean update = false;
List<Connection> nweConnections = new ArrayList<>(connections);
for (int i = 0; i < connections.size(); i++) {
Connection connection = nweConnections.get(i);
if (connection.isConnectionLost()) {
Connection newConnection = new SimpleConnection(((SimpleConnection) connection).getServer());
nweConnections.set(i, newConnection);
update = true;
}
}
if (update) {
connections = nweConnections;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment