Simple pool of Threads : Thread Pool « Threads « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Threads » Thread Pool 




Simple pool of Threads
Simple pool of Threads
   

/*
 * Copyright (c) 1998 - 2005 Versant Corporation
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Versant Corporation - initial API and implementation
 */

import java.util.LinkedList;
import java.util.Iterator;
import java.util.HashSet;

/**
 * Simple pool of Threads.
 */
public class ThreadPool {

    private String name;
    private HashSet active = new HashSet();
    private LinkedList idle = new LinkedList();
    private int idleCount;
    private int maxActive = 10;
    private int maxIdle = 3;
    private int lastThreadId;
    private boolean closed;

    public ThreadPool(String name) {
        this.name = name;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public synchronized int getActiveCount() {
        return active.size();
    }

    public synchronized int getIdleCount() {
        return idleCount;
    }

    /**
     * Close the pool, stopping all threads. This does not wait for the
     * threads to actually stop before returning. This is a NOP if the
     * pool has already been closed.
     */
    public synchronized void close() {
        if (closed) {
            return;
        }
        closed = true;
        for (Iterator i = idle.iterator(); i.hasNext()) {
            Worker w = (Worker)i.next();
            w.terminate();
        }
        idle = null;
        idleCount = 0;
        for (Iterator i = active.iterator(); i.hasNext()) {
            Worker w = (Worker)i.next();
            w.terminate();
        }
        active = null;
    }

    /**
     * Executed runnable using a Thread from the pool. This will block for
     * timeoutMs and forever if this is 0. Returns true if the task is
     * being executed (i.e. a Thread was available) or false if not (i.e.
     * pool full).
     */
    public synchronized boolean execute(Runnable runnable, int timeoutMs) {
        if (closed) {
            throw new IllegalStateException("Pool has been closed");
        }
        Worker t;
        if (idleCount == 0) {
            for (; isFull()) {
                try {
                    wait(timeoutMs);
                    if (isFull()) {
                        return false;
                    }
                catch (InterruptedException e) {
                    // ignore
                }
            }
            t = new Worker();
        else {
            t = (Worker)idle.removeFirst();
            --idleCount;
        }
        active.add(t);
        t.execute(runnable);
        return true;
    }

    protected boolean isFull() {
        return active.size() >= maxActive;
    }

    private synchronized void finishedWork(Worker t) {
        if (!closed) {
            active.remove(t);
            if (idleCount >= maxIdle) {
                t.terminate();
            else {
                idle.addLast(t);
                ++idleCount;
            }
        }
    }

    private class Worker extends Thread {

        private boolean stopFlag;
        private Runnable runnable;

        public Worker() {
            super(name + " " + ++lastThreadId);
            setDaemon(true);
        }

        /**
         * Executed runnable.
         */
        public void execute(Runnable runnable) {
            this.runnable = runnable;
            if (!isAlive()) {
                start();
            else {
                synchronized (this) {
                    notify();
                }
            }
        }

        /**
         * Stop this thread as soon as possible.
         */
        public void terminate() {
            stopFlag = true;
            interrupt();
        }

        public void run() {
            for (; !stopFlag; ) {
                try {
                    runnable.run();
                catch (Throwable e) {
                    if (instanceof ThreadDeath) {
                        throw (ThreadDeath)e;
                    }
                }
                runnable = null;
                finishedWork(this);
                if (stopFlagbreak;
                synchronized (this) {
                    try {
                        wait();
                    catch (InterruptedException e) {
                        // ignore
                    }
                }
            }
        }

    }

}

   
    
    
  














Related examples in the same category
1.Defining a thread for a thread poolDefining a thread for a thread pool
2.Thread pool demo
3.Thread Pools 1
4.Thread Pools 2Thread Pools 2
5.Thread pool
6.Thread Pool 2Thread Pool 2
7.Thread Pool TestThread Pool Test
8.JDK1.5 provides a mechanism to create a pool a scheduled task
9.Very basic implementation of a thread poolVery basic implementation of a thread pool
10.Thread Cache
11.Worker thread pool
12.Create a new thread for the thread pool. The create thread will be a daemon thread.
13.Simple thread pool. A task is executed by obtaining a thread from the poolSimple thread pool. A task is executed by obtaining a thread from the pool
14.Simple object pool. Based on ThreadPool and few other classes
15.A utility class that receives a collection of tasks to execute internally and then distributes the tasks among a thread pool.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.