任务队列_推演

有这么一类服务:单个任务的时间很短,但请求量很大。例如web服务。
 
如何设计这样的服务器?
 
方案一:每当一个请求到达时创建一个新的Thread,然后在新线程里执行请求;
【不足】①为每一个请求创建的Thread 在创建和销毁时消耗的系统资源比处理request本身消耗系统资源更大;②当请求量很大时,一个JVM里创建Thread过多,导致内存耗完或切换过度,需要限制请求量;
 
【改进】使用线程池;首先解决了线程频繁创建销毁的开销;其次,限制了最大请求量,防止了系统资源不足;
 
方案二:把请求放到一个任务队列,交给一个Thread统一处理;
【不足】响应不及时,吞吐量太低;
 
方案三:线程池和一个任务队列;
 
任务队列一般都有相关监视器功能,比如超时,用链表实现;
 
import java.util.LinkedList;

public class WorkQueue {
    private final int nThreads;
    private final PoolWorker[] threads;
    private final LinkedList queue;

    public WorkQueue(int nThreads) {
        this.nThreads = nThreads;
        queue = new LinkedList();
        threads = new PoolWorker[nThreads];
        for (int i = 0; i < nThreads; i++) {
            threads[i] = new PoolWorker();
            threads[i].start();
        }
    }

    public void execute(Runnable r) {
        synchronized (queue) {
            queue.addLast(r);
            queue.notify();
        }
    }

    private class PoolWorker extends Thread {
        public void run() {
            Runnable r;
            while (true) {
                synchronized (queue) {
                    while (queue.isEmpty()) {
                        try {
                            queue.wait();
                        } catch (InterruptedException ignored) {
                        }
                    }
                    r = (Runnable) queue.removeFirst();
                }
                // If we don't catch RuntimeException,
                // the pool could leak threads
                try {
                    r.run();
                } catch (RuntimeException e) {
                    // You might want to log something here
                }
            }
        }
    }
}
View Code

 

posted @ 2016-03-24 15:34  Java扫地僧  阅读(131)  评论(0)    收藏  举报