Search This Blog

A simple Java thread pool implementation for short lived tasks

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 65 66 67
import java.util.Stack;

public class ThreadPool {

    private static class Worker implements Runnable {

        private Runnable _runnable;

        public synchronized void execute(final Runnable sc) {
            _runnable = sc;
            notify();
        }

        @Override
        public synchronized void run() {
            try {
                final boolean running = true;
                while (running) {
                    while (_runnable == null) {
                        try {
                            wait();
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            ie.printStackTrace();
                        }
                    }
                    try {
                        _runnable.run();
                    } catch (RuntimeException re) {
                        // Catch RuntimeException to avoid thread leaking
                        re.printStackTrace();
                    }
                    _runnable = null;
                    completed(this);
                }
            } finally {
                terminated(this);
            }
        }
    }

    private static Stack<Worker> _workers = new Stack<Worker>();
    private static int _tid;

    public static void execute(Runnable sc) {
        executor().execute(sc);
    }

    private static synchronized Worker executor() {
        if (_workers.isEmpty()) {
            final Worker e = new Worker();
            final Thread t = new Thread(e, "Worker id=" + _tid++);
            t.start();
            return e;
        }
        return _workers.pop();
    }

    private static synchronized void completed(Worker e) {
        _workers.push(e);
    }

    private static synchronized void terminated(Worker e) {
        
    }

}



see also

  • http://tutorials.jenkov.com/java-concurrency/thread-pools.html

No comments:

Post a Comment