Simple thread pool. A task is executed by obtaining a thread from the pool : Thread Pool « Threads « Java

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. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Threads » Thread PoolScreenshots 
Simple thread pool. A task is executed by obtaining a thread from the pool
Simple thread pool. A task is executed by obtaining a thread from the pool
  
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

import java.util.ArrayList;
import java.util.List;


/** Simple thread pool. A task is executed by obtaining a thread from
 * the pool
 */
public class ThreadPool {
  /** The thread pool contains instances of {@link ThreadPool.Task}.
   */
  public interface Task {
    /** Performs the task.
     @throws Throwable The task failed, and the worker thread won't be used again.
     */
    void run() throws Throwable;
  }

    /** A task, which may be interrupted, if the pool is shutting down. 
     */
    public interface InterruptableTask extends Task {
        /** Interrupts the task.
         @throws Throwable Shutting down the task failed.
         */
        void shutdown() throws Throwable;
    }

    private class Poolable {
        private boolean shuttingDown;
        private Task task;
        private Thread thread;
        Poolable(ThreadGroup pGroup, int pNum) {
            thread = new Thread(pGroup, pGroup.getName() "-" + pNum){
                public void run() {
                    while (!isShuttingDown()) {
                        final Task t = getTask();
                        if (t == null) {
                            try {
                                synchronized (this) {
                                    if (!isShuttingDown()  &&  getTask() == null) {
                                        wait();
                                    }
                                }
                            catch (InterruptedException e) {
                                // Do nothing
                            }
                        else {
                            try {
                                t.run();
                                resetTask();
                                repool(Poolable.this);
                            catch (Throwable e) {
                                discard(Poolable.this);
                                resetTask();
                            }
                        }
                    }
                }
            };
            thread.start();
        }
        synchronized void shutdown() {
            shuttingDown = true;
            final Task t = getTask();
            if (t != null  &&  t instanceof InterruptableTask) {
                try {
                    ((InterruptableTaskt).shutdown();
                catch (Throwable th) {
                    // Ignore me
                }
            }
            task = null;
            synchronized (thread) {
                thread.notify();
            }
        }
        private synchronized boolean isShuttingDown() { return shuttingDown; }
        String getName() { return thread.getName()}
        private synchronized Task getTask() {
            return task;
        }
        private synchronized void resetTask() {
            task = null;
        }
        synchronized void start(Task pTask) {
            task = pTask;
            synchronized (thread) {
                thread.notify();
            }
        }
    }

  private final ThreadGroup threadGroup;
  private final int maxSize;
  private final List waitingThreads = new ArrayList();
  private final List runningThreads = new ArrayList();
  private final List waitingTasks = new ArrayList();
  private int num;


  /** Creates a new instance.
   @param pMaxSize Maximum number of concurrent threads.
   @param pName Thread group name.
   */
  public ThreadPool(int pMaxSize, String pName) {
    maxSize = pMaxSize;
    threadGroup = new ThreadGroup(pName);
  }

  synchronized void discard(Poolable pPoolable) {
    pPoolable.shutdown();
        runningThreads.remove(pPoolable);
        waitingThreads.remove(pPoolable);
  }

  synchronized void repool(Poolable pPoolable) {
        if (runningThreads.remove(pPoolable)) {
            if (maxSize != 0  &&  runningThreads.size() + waitingThreads.size() >= maxSize) {
                discard(pPoolable);
            else {
                waitingThreads.add(pPoolable);
                if (waitingTasks.size() 0) {
                    Task task = (TaskwaitingTasks.remove(waitingTasks.size() 1);
                    startTask(task);
                }
            }
        else {
            discard(pPoolable);
        }
  }

  /** Starts a task immediately.
   @param pTask The task being started.
   @return True, if the task could be started immediately. False, if
   * the maxmimum number of concurrent tasks was exceeded. If so, you
   * might consider to use the {@link #addTask(ThreadPool.Task)} method instead.
   */
  public synchronized boolean startTask(Task pTask) {
    if (maxSize != 0  &&  runningThreads.size() >= maxSize) {
      return false;
    }
        Poolable poolable;
    if (waitingThreads.size() 0) {
        poolable = (PoolablewaitingThreads.remove(waitingThreads.size()-1);
    else {
            poolable = new Poolable(threadGroup, num++);
    }
    runningThreads.add(poolable);
        poolable.start(pTask);
    return true;
  }

  /** Adds a task for immediate or deferred execution.
   @param pTask The task being added.
   @return True, if the task was started immediately. False, if
   * the task will be executed later.
   */
  public synchronized boolean addTask(Task pTask) {
    if (startTask(pTask)) {
      return true;
    }
    waitingTasks.add(pTask);
    return false;
  }

  /** Closes the pool.
   */
  public synchronized void shutdown() {
        while (!waitingThreads.isEmpty()) {
            Poolable poolable = (PoolablewaitingThreads.remove(waitingThreads.size()-1);
            poolable.shutdown();
        }
        while (!runningThreads.isEmpty()) {
            Poolable poolable = (PoolablerunningThreads.remove(runningThreads.size()-1);
            poolable.shutdown();
        }
  }

  /** Returns the maximum number of concurrent threads.
   @return Maximum number of threads.
   */
  public int getMaxThreads() { return maxSize; }

  /** Returns the number of threads, which have actually been created,
     * as opposed to the number of currently running threads.
   */
    public synchronized int getNumThreads() { return num; }
}

   
    
  
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. Simple pool of ThreadsSimple pool of Threads
12. Worker thread pool
13. Create a new thread for the thread pool. The create thread will be a daemon thread.
14. Simple object pool. Based on ThreadPool and few other classes
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.