-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionExecutor.java
More file actions
66 lines (52 loc) · 1.99 KB
/
ConnectionExecutor.java
File metadata and controls
66 lines (52 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package stackserver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ConnectionExecutor extends ThreadPoolExecutor {
private static List<ConnectionHandler> connectionList = Collections.synchronizedList(new ArrayList<ConnectionHandler>());
// Set up a threadpool with a limit set through the connectionLimit arg
public ConnectionExecutor(int connectionLimit) {
super(connectionLimit, connectionLimit, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
public void killAllConnections() {
for (ConnectionHandler handler : connectionList) {
System.out.println("Killing connections");
handler.interrupt();
}
}
public void killOldestHandler(){
connectionList.get(0).interrupt();
}
public int getOldestHandlerRuntime(){
long timeNow = System.currentTimeMillis();
long oldestThreadTime = connectionList.get(0).getRequestStartTime();
int diff = (int)((timeNow - oldestThreadTime)/1000);
return diff;
}
public boolean threadsAvailable(){
if (getActiveCount() >= 100) return false;
// else
return true;
}
public boolean hasSlowThread(){
if(getOldestHandlerRuntime() >= 10) return true;
return false;
}
public ConnectionHandler getHandler(int index) {
ConnectionHandler handler = connectionList.get(index);
return handler;
}
// Parent class {@link ThreadPoolExecutor} provides 'hook' methods that fire before and after a thread executes.
// We just want to keep track of the connection reference with a list for now.
@Override
protected synchronized void beforeExecute(Thread t, Runnable connection) {
connectionList.add((ConnectionHandler)connection);
}
@Override
protected synchronized void afterExecute(Runnable connection, Throwable throwable) {
connectionList.remove((ConnectionHandler)connection);
}
};