1、Guarded Suspension意为暂停保护,其核心思想是仅当服务进程准备好时,才提供服务。设想一种场景,服务器可能会在很短时间内承受大量的客户端请求,客户端请求的数量可能超过服务器本身的即时处理能力,而服务端程序又不能丢弃任何一个客户请求。此时,最佳的处理方案莫过于让客户端要求进行排队,由服务端程序一个接一个处理。这样,既保证了所有的客户端请求均不丢失,同时也避免了服务器由于同时处理太多的请求而崩溃。
2、Guarded Suspension模式的结构
Guarded Suspension模式的主要成员有:Request、RequestQueue、ClientThread、ServerThread
Request:表示客户端请求
RequestQueue:用于保存客户端请求队列
ClientThread:客户端进程
ServerThread:服务器进程
3、Guarded Suspension模式的实现
public class Request {
private String name;
public Request(){}
public Request(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class RequestQueue {
private LinkedList<Request> queue = new LinkedList();
public void putRequest(Request request){
synchronized (queue){
queue.addLast(request);
queue.notifyAll();
}
}
public Request getRequest(){
synchronized (queue){
while(queue.size() == 0){
try {
queue.wait();
} catch (InterruptedException e) {
System.out.println("RequestQueue InterruptedException");
return null;
}
}
return queue.removeFirst();
}
}
}
public class ClientThread extends Thread {
private final RequestQueue queue;
private final Random random;
private final String name;
public ClientThread(RequestQueue queue, String name) {
this.queue = queue;
this.name = name;
random = new Random(System.currentTimeMillis());
}
@Override
public void run() {
for(int i = 0 ; i < 100 ; i ++){
queue.putRequest(new Request(name));
System.out.println("client -> request " + name);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ServerThread extends Thread {
private final RequestQueue queue;
private final Random random ;
private volatile boolean closed;
public ServerThread(RequestQueue queue) {
this.queue = queue;
random = new Random(System.currentTimeMillis());
}
@Override
public void run() {
while (!closed){
Request request = queue.getRequest();
if (request == null){
System.out.println("request is null !!");
continue;
}
System.out.println("server -> handle request " + request.getName());
try {
Thread.sleep(random.nextInt(100));
} catch (InterruptedException e) {
System.out.println("ServerThread InterruptedException");
}
}
}
public void close(){
closed = true;
interrupt();
}
}
public class TestClient {
public static void main(String[] args) throws InterruptedException {
RequestQueue queue = new RequestQueue();
ClientThread hello_server = new ClientThread(queue, "hello server");
hello_server.start();
ServerThread serverThread = new ServerThread(queue);
serverThread.start();
}
}