Results returned directly from Thread Pool?

Hi there. I wonder is there any example showing an Applicating which use thread pool to process multiple requests and return the results directly back to the client.
Eg:
When calling int doProcess(Runnable process), how can I get some value return from that method?
Most example that I've seen were just showing a void run() method with some print statements.

you'll need to use synchronized threads in your run method to ensure that the proper value is returned. look for synchronized thread examples. most examples using one or two threads run in a run() method are gibberish and have no thought put into them.

Similar Messages

  • Thread pools problem

    How do we know that a given task(implementing Callable) in a thread pool (ThreadPoolExecutor) is completed ?
    I know that we can use the get( ) method of Future class... but for that the current thread has to wait until the Task given to the Thread pool completed.
    But I want to know ..Is it possible to get (asynchronus)notification from Thread pool when one of the submitted task finish.

    What about using the isDone() method of Future or even get(timeout, TimeUnit.SECONDS).
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html

  • I cannot install a previously purchased version of acrobat 9 pro downloaded from the site.  Returns message at final install steps "invalid serial number." I had copied it and pasted it directly from "My Adobe".  What to do?

    I cannot install a previously purchased version of acrobat 9 pro downloaded from the site.  Returns message at final install steps "invalid serial number." I had copied it and pasted it directly from "My Adobe".  What to do?

    Hi hgratz,
    Considering 'invalid serial number' error for Acrobat 9, I would suggest you to please refer the KB doc link mentioned below:
    Error "Invalid serial number" | Acrobat 9 | CS4
    Let me know if that helps.
    Regards,
    Anubha

  • HT4061 I am receiving return e-mails saying undeliverable mail was sent using my e-mail addy as the "from" addy. It is spam mail and some has been sent to U.S. military. It is not coming directly from my e-mail/ i-cloud account. How do I stop it?

    I am receiving returne postmaster e-mails saying e-mails were not deliverable, and some say they were blocked as being spam mail because they were sent to U.S. military addresses. The e-mails are coming from an outside source and are not being sent directly from my e-mail, but whoever is doing it is putty my address in as the sender. How do I stop this?

    at this point the best you could do would be to delete your email account, or ignore the emails

  • 100% thread pool/CPU usage prevent MII Applications from working

    Hello to all,
    our MII Applications were running on MII 11.5 (windowsserver 2003, with IIS) without any problems.
    We migrated these MII Applications  to SAP xMII Version 12.0 SP8, SAP NW 7.00 SP20, Java HotSpot(TM) 64-Bit Server VM (build 1.4.2_22-rev-b03, mixed mode).
    Since then we faced several problems that prevent the MII Applications from working, e.g.
    - 100% application thread pool usage rate
    - 100% CPU usage
    - awful lot of http connections
    Several sap support calls didn't find the root cause.
    Workaround: restart sap system weekly
    Does anyone has any idea how to go on?
    Thanks
    Simone

    Hi Mike,
    sap support told us to install this Java version.
    Furthermore SAP Note 716604 says "do not use J2SE 5.0" and "Currently, we recommend 1.4.2_24 b06".
    Any more ideas?
    Regards,
    Simone

  • ITunes 10.7 Update returns error (-1003) & remains in App Store despite updating iTunes directly from iTunes webpage several times & currently running latest version 11.0.5 (5)

    I have experienced this problem since purchasing a brand new MacBook in October 2012, basically the App Store permanently displays "1 Update Available" for iTunes 10.7 but clicking the "Update" button only results in the following error "A server with the specified hostname could not be found.(-1003)" so I have always had to go around the App Store & download & install iTunes updates directly from the iTunes webpage.  I am currently running the latest version of iTunes 11.0.5 (5) & what I believe is the latest version of OS X 10.8.4 (12E55) & I simply wish to stop the App Store displaying this update that doesn't work anyway & relates to a year old version of iTunes!!! 
    Note: It may or may not be of importance but the same problem was also happening for iPhoto & iMovie but I was able to locate fixes for these issues which entailed changing a filename in both applications' "Contents" folders from "_MASReceipt" to "_MASReceipt_FAULTY" (although I believe I could have renamed it anything!)  I obviously tried a similar thing for iTunes & App Store separately but unlike iMovie & iPhoto which were fixed immediately the recommended changes were made, these modifications did not resolve the issue which persists to this day & isn't critical but is just annoying!!!

    Search for "iTunes" in Spotlight and make sure you don't have an outdated copy lying around, perhaps on a backup volume.

  • Show preview directly from Spotlight results

    Hi,
    I would like to show a preview of the contents (like pressing Space in the Finder), directly from the Spotlight Quick Results list (top right screen).
    Is this possible ? Selecting the entry en pressing Space does not work here.
    Rgds, Jaap

    Yes, I know how to press Space in a Finder window. My question was how to do it in the quick search results. That's what I use most of the time. Is this possible ?

  • The problem in the thread pool implemented by myself

    Hello, I need to a thread pool in J2ME CDC 1.0 + FP 1.0, so I implemented a simple one by myself that also meets my own requirement.
    Here is the main idea:
    The thread pool creates a fixed number of threads in advance. When a task comes, it is put in the waiting list. All threads tries to get the tasks from the waiting list. If no task exists, the threads wait until someone wakes them up.
    Here are the requirements from myself:
    1. when a task has finished its work in one execution, it is put in the waiting list for the next run.
    2. the task can control the delay between when the task owner tries to put it in the waiting list and when the task is actually put in the waiting list. I need this function because sometimes I don't want the tasks to run too often and want to save some CPU usage.
    In my program, I creates two thread pools. In one pool, every task don't use the delay, and the thread pool works very well. The other pool has the tasks that use the delay, and sometimes, as I can see from the printed information, there are many tasks in the waiting list but 0 or 1 thread executes tasks. It seems that the waiting threads cannot wake up when new tasks comes.
    I suspect the code in addTask(), but cannot find the reason why it fails. Could anyone please help me find out the bug in my code? I put the code of thread pool below
    Thank you in advance
    Zheng Da
    ThreadPool.java
    package j2me.concurrent;
    import java.util.LinkedList;
    import java.util.Timer;
    import java.util.TimerTask;
    import alvis.general.Util;
    public class ThreadPool {
         private int maxQueueSize;
         private boolean running = true;
         private Thread[] threads;
         private LinkedList tasks = new LinkedList();
         private Timer timer = new Timer(true);
         private AtomicInteger usingThreads = new AtomicInteger(0);
         private synchronized boolean isRunning() {
              return running;
         private synchronized void stopRunning() {
              running = false;
         private synchronized PoolTask getTask() {
              while (tasks.isEmpty() && isRunning()) {
                   try {
                        this.wait();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              if (tasks.isEmpty())
                   return null;
              // Util.log.info(Thread.currentThread().getName() +
              // " gets a task, left tasks: " + tasks.size());
              return (PoolTask) tasks.removeFirst();
         private synchronized void addTaskNoDelay(PoolTask task) {
              tasks.addLast(task);
              notifyAll();
         private synchronized void addTask(final PoolTask task) {
              long delay = task.delay();
              if (delay == 0) {
                   addTaskNoDelay(task);
              } else {
                   timer.schedule(new TimerTask() {
                        public void run() {
                             addTaskNoDelay(task);
                   }, delay);
         private synchronized int numTasks() {
              return tasks.size();
         private class PoolThread extends Thread {
              public void run() {
                   Util.poolThreads.inc();
                   while (isRunning()) {
                        PoolTask task = getTask();
                        if (task == null) {
                             Util.poolThreads.dec();
                             return;
                        usingThreads.inc();
                        long currentTime = System.currentTimeMillis();
                        task.run();
                        long elapsedTime = System.currentTimeMillis() - currentTime;
                        if (elapsedTime > 100)
                             System.err.println(task.toString() + " takes " + ((double) elapsedTime)/1000 + "s");
                        usingThreads.dec();
                        if (!task.finish()) {
                             addTask(task);
                   Util.poolThreads.dec();
         public ThreadPool(int size, int taskQueueSize) {
              maxQueueSize = taskQueueSize;
              threads = new Thread[size];
              for (int i = 0; i < threads.length; i++) {
                   threads[i] = new PoolThread();
                   threads.start();
         public synchronized boolean executor(PoolTask task) {
              if (!isRunning()) {
                   return false;
              Util.log.info("Thread Pool gets " + task + ", there are "
                        + numTasks() + " waiting tasks");
              if (numTasks() >= maxQueueSize) {
                   return false;
              addTask(task);
              return true;
         public synchronized void destroy() {
              stopRunning();
              timer.cancel();
              // TODO: I am not sure it can wake up all threads and destroy them.
              this.notifyAll();
         public synchronized void printSnapshot() {
              System.err.println("using threads: " + usingThreads + ", remaining tasks: " + tasks.size());
    PoolTask.javapackage j2me.concurrent;
    public interface PoolTask extends Runnable {
         * It shows if the task has already finished.
         * If it isn't, the task will be put in the thread pool for the next execution.
         * @return
         boolean finish();
         * It shows the delay in milliseconds that the task is put in the thread pool.
         * @return
         long delay();

    are receiving/sends tasks packets time consuming operation in your case or not? if it is not you do not need to use thread pools at all. you can create a queue like in your code through the linked list and dispatch this queue periodically with minimum monitor usage. try this.
    import java.util.LinkedList;
    public class PacketDispatcher extends Thread {
        LinkedList list = new LinkedList();
        public PacketDispatcher (String name) {
            super(name);
        public void putTask(Task task) {
            synchronized (list) {
                list
                        .add(task);
                list.notify();
        public void run() {
            while (true/* your condition */) {
                Task task = null;
                synchronized (list) {
                    while (list.isEmpty())
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                    task = (Task)list
                            .poll();
                if (task == null) {
                    try {
                        Thread
                                .sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    continue;
                task
                        .run();
                if (!task.isFinished()) {
                    putTask(task);
                Thread
                        .yield();
        public static void main(String[] args) {
            // just for test
            try {
                Thread.sleep (10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            PacketDispatcher dispatcher = new PacketDispatcher("Packet Dispatcher");
            Task task = new Task();
            dispatcher.putTask(task);
            dispatcher.start();
            try {
                Thread.sleep (10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            Task task2 = new Task();
            dispatcher.putTask(task2);
    class Task {
        long result = 0;
        public boolean isFinished () {
            if (getResult() >= 10000000) {
                return true;
            return false;
        public void run() {
            for (int i = 0; i < 1000; i++) {
                result += i;
        public long getResult () {
            return result;       
    }

  • Thread pool library

    Hello all,
    Does anybody know an open-source library that provides a thread pool with the following behavior?
    When a task is submitted...
    if (there are idle threads in the pool) {
        use an idle thread to execute the task.
    } else {
        if (currentThreadCount < maximumPoolSize) {
            create new thread to execute the task.
        } else {
            put the task in the queue.
            (tasks in the queue will be processed when threads are available).
    }If a thread remains idle for X time, it dies.
    Thank you

    I ran your code and it ran it just fine, I prefixed your println to print out the currentTimeMillis to show it ran right after each other.
    System.out.println(System.currentTimeMillis() +  "{code}
    Here is the result:
    1244482518471 Starting main.
    1244482518483 Running a task
    Here is code fragments from ThreadPoolExecutor I generated my sudo code from.
    {code}
         * Executes the given task sometime in the future.  The task
         * may execute in a new thread or in an existing pooled thread.
         * If the task cannot be submitted for execution, either because this
         * executor has been shutdown or because its capacity has been reached,
         * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
         * @param command the task to execute
         * @throws RejectedExecutionException at discretion of
         * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
         * for execution
         * @throws NullPointerException if command is null
        public void execute(Runnable command) {
            if (command == null)
                throw new NullPointerException();
            if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
                if (runState == RUNNING && workQueue.offer(command)) {
                    if (runState != RUNNING || poolSize == 0)
                        ensureQueuedTaskHandled(command);
                else if (!addIfUnderMaximumPoolSize(command))
                    reject(command); // is shutdown or saturated
         * Creates and starts a new thread running firstTask as its first
         * task, only if fewer than corePoolSize threads are running
         * and the pool is not shut down.
         * @param firstTask the task the new thread should run first (or
         * null if none)
         * @return true if successful
        private boolean addIfUnderCorePoolSize(Runnable firstTask) {
            Thread t = null;
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                if (poolSize < corePoolSize && runState == RUNNING)
                    t = addThread(firstTask);
            } finally {
                mainLock.unlock();
            if (t == null)
                return false;
            t.start();
            return true;
         * Rechecks state after queuing a task. Called from execute when
         * pool state has been observed to change after queuing a task. If
         * the task was queued concurrently with a call to shutdownNow,
         * and is still present in the queue, this task must be removed
         * and rejected to preserve shutdownNow guarantees.  Otherwise,
         * this method ensures (unless addThread fails) that there is at
         * least one live thread to handle this task
         * @param command the task
        private void ensureQueuedTaskHandled(Runnable command) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            boolean reject = false;
            Thread t = null;
            try {
                int state = runState;
                if (state != RUNNING && workQueue.remove(command))
                    reject = true;
                else if (state < STOP &&
                         poolSize < Math.max(corePoolSize, 1) &&
                         !workQueue.isEmpty())
                    t = addThread(null);
            } finally {
                mainLock.unlock();
            if (reject)
                reject(command);
            else if (t != null)
                t.start();
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How can I use the same thread pool implementation for different tasks?

    Dear java programmers,
    I have written a class which submits Callable tasks to a thread pool while illustrating the progress of the overall procedure in a JFrame with a progress bar and text area. I want to use this class for several applications in which the process and consequently the Callable object varies. I simplified my code and looks like this:
            threadPoolSize = 4;
            String[] chainArray = predock.PrepareDockEnvironment();
            int chainArrayLength = chainArray.length;
            String score = "null";
            ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
            CompletionService<String> referee = new ExecutorCompletionService<String>(executor);
            for (int i = 0; i < threadPoolSize - 1; i++) {
                System.out.println("Submiting new thread for chain " + chainArray);
    referee.submit(new Parser(chainArray[i]));
    for (int chainIndex = threadPoolSize; chainIndex < chainArrayLength; chainIndex++) {
    try {
    System.out.println("Submiting new thread for chain " + chainArray[chainIndex]);
    referee.submit(new Parser(chainArray[i]));
    score = referee.poll(10, TimeUnit.MINUTES).get();
    System.out.println("The next score is " + score);
    executor.shutdown();
    int index = chainArrayLength - threadPoolSize;
    score = "null";
    while (!executor.isTerminated()) {
    score = referee.poll(10, TimeUnit.MINUTES).get();
    System.out.println("The next score is " + score);
    index++;
    My question is how can I replace Parser object with something changeable, so that I can set it accordingly whenever I call this method to conduct a different task?
    thanks,
    Tom                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    OK lets's start from the beginning with more details. I have that class called ProgressGUI which opens a small window with 2 buttons ("start" and "stop"), a progress bar and a text area. It also implements a thread pool to conducts the analysis of multiple files.
    My main GUI, which is much bigger that the latter, is in a class named GUI. There are 3 types of operations which implement the thread pool, each one encapsulated in a different class (SMAP, Dock, EP). The user can set the necessary parameters and when clicking on a button, opens the ProgressGUI window which depicts the progress of the respective operation at each time step.
    The code I posted is taken from ProgressGui.class and at the moment, in order to conduct one of the supported operations, I replace "new Parser(chainArray)" with either "new SMAP(chainArray[i])", "new Dock(chainArray[i])", "new EP(chainArray[i])". It would be redundant to have exactly the same thread pool implementation (shown in my first post) written 3 different times, when the only thing that needs to be changed is "new Parser(chainArray[i])".
    What I though at first was defining an abstract method named MainOperation and replace "new Parser(chainArray[i])" with:
    new Callable() {
      public void call() {
        MainOperation();
    });For instance when one wants to use SMAP.class, he would initialize MainOperation as:
    public abstract String MainOperation(){
        return new SMAP(chainArray));
    That's the most reasonable explanation I can give, but apparently an abstract method cannot be called anywhere else in the abstract class (ProgressGUI.class in my case).
    Firstly it should be Callable not Runnable.Can you explain why? You are just running a method and ignoring any result or exception. However, it makes little difference.ExecutorCompletionService takes Future objects as input, that's why it should be Callable and not Runnable. The returned value is a score (String).
    Secondly how can I change that runMyNewMethod() on demand, can I do it by defining it as abstract?How do you want to determine which method to run?The user will click on the appropriate button and the GUI will initialize (perhaps implicitly) the body of the abstract method MainOperation accordingly. Don't worry about that, this is not the point.
    Edited by: tevang2 on Dec 28, 2008 7:18 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Threads: Pooling and groups

    Hello there! I need to implement a solution that will use threads, I write down my problem, to be more precisely on the questions.
    The scenario:
    An extrator, reads from a flat file, and insert into a table.
    Another process runs threads to read this table, perform an ETL and then insert in antoher table. I'm considering that the file read process's time is <<< (much smaller) than the ETL, due the transformations involved.
    So my first solution was to use thread pooling (Im reading about, and already have some implementations), since I dont want to have more than a few threads running at same time (let's say 5-6).
    Ok my first Ideia was to do something like this:
    a main class that will run a thread (the text file extractor), this will be done from the pool of threads, so I have n-1 threads left.
    This thread would read the lines and at each 10k read, commit the result, and now its the tricky part, warn its parent process (main class) that it already processed 10k registers. The main class would know that and then start a new thread (the ETL thread, reading from 0-10k) now I have n-2 threads left. The process would go on, since the text thread is faster, It would continue warning the main class, that it had processed 10k registers and main class would continue dispatching new threads, untill it reaches a maximum number (controled by the pool). The pool would be responsible to create its own list of waiting threads to run.
    My main problem is to make sure that the text thread can warn the main thread. Can someone point me so directions to it? a tutorial, a hint, anything would help

    Thread.sleep()
    Thread.interrupt()
    Well, I'm sorry but I dont think ? I made my self
    clear. I need to know how to warn my parent thread not
    put the one I'm running in sleep or terminate it.Well. A call to interrupt() does not terminate another thread,
    rather, like the name indicates, it interrupts it, but only if
    the thread to be interrupted is blocking on a sleep(), join(), or wait() call or is blocking on interruptible I/O (java.nio.channels stuff).
    If the thread is not currently blocking, a flag is set.
    If there is no need for the parent to sleep() you can just call interrupted() to check the flag at regular intervals.

  • How to get return values from stored procedure to ssis packge?

    Hi,
    I need returnn values from my stored procedure to ssis package -
    My procedure look like  and ssis package .Kindly help me to oget returnn value to my ssis package
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: <Author,,Name>
    -- Create date: <Create Date,,>
    -- Description: <Description,,>
    -- =============================================
    ALTER PROCEDURE [TSC]
    -- Add the parameters for the stored procedure here
    @P_STAGE VARCHAR(2000)
    AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    --SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
    truncate table [INPUTS];
    INSERT
    INTO
    [INPUTS_BASE]
    SELECT
    [COLUMN]
    FROM [INPUTS];
    RETURN
    END
    and i am trying to get the return value from execute sql task and shown below
    and i am taking my returnn value to result set variable

    You need to have either OUTPUT parameters or use RETURN statement to return a value in stored procedures. RETURN can only return integer values whereas OUTPUT parameters can be of any type
    First modify your procedure to define return value or OUTPUT parameter based on requirement
    for details see
    http://www.sqlteam.com/article/stored-procedures-returning-data
    Once that is done in SSIS call sp from Execute SQL Task and in parameter mapping tabe shown above add required parameters and map them to variables created in SSIS and select Direction as Output or Return Value based on what option you used in your
    procedure.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • A good design for a single thread pool manager using java.util.concurrent

    Hi,
    I am developing a client side project which in distinct subparts will execute some tasks in parallel.
    So, just to be logorroic, something like that:
    program\
                \--flow A\
                           \task A1
                           \task A2
                \--flow B\
                            \task B1
                            \task B2
                            \...I would like both flow A and flow B (and all their launched sub tasks) to be executed by the same thread pool, because I want to set a fixed amount of threads that my program can globally run.
    My idea would be something like:
    public class ThreadPoolManager {
        private static ExecutorService executor;
        private static final Object classLock = ThreadPoolManager.class;
         * Returns the single instance of the ExecutorService by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getExecutorService() {
            synchronized (classLock) {
                if (executor != null) {
                    return executor;
                } else {
                    // TODO: put the dimension of the FixedThreadPool in a property
                    executor = Executors.newFixedThreadPool(50);
                return executor;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
    }The tasks I have to execute will be of type Callable, since I expect some results, so you see an ExecutorService interface above.
    The flaws with this design is that I don't prevent the use (for example) of executor.shutdownNow(), which would cause problems.
    The alternative solution I have in mind would be something like having ThreadPoolManager to be a Singleton which implements ExecutorService, implementing all the methods with Delegation to an ExecutorService object created when the ThreadPoolManager object is instantiated for the first time and returned to client:
    public class ThreadPoolManager implements ExecutorService {
        private static ThreadPoolManager pool;
        private static final Object classLock = ThreadPoolManager.class;
        private ExecutorService executor;
         * Returns the single instance of the ThreadPoolManager by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getThreadPoolManager() {
            synchronized (classLock) {
                if (pool !=null) {
                    return pool;
                } else {
                    // create the real thread pool
                    // TODO: put the dimension of the FixedThreadPool in a property
                    // file
                    pool = new ThreadPoolManager();
                    pool.executor = Executors.newFixedThreadPool(50);
                    // executor = Executors.newCachedThreadPool();
                    return pool;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
        /* ======================================== */
        /* implement ExecutorService interface methods via delegation to executor
         * (forbidden method calls, like shutdownNow() , will be "ignored")
          // .....I hope to have expressed all the things, and hope to receive an answer that clarifies my doubts or gives me an hint for an alternative solution or an already made solution.
    ciao
    Alessio

    Two things. Firstly, it's better to use     private static final Object classLock = new Object();because that saves you worrying about whether any other code synchronises on it. Secondly, if you do decide to go for the delegation route then java.lang.reflect.Proxy may be a good way forward.

  • Should Collections be used as return types across threads?

    I am wondering when, if ever, it is appropriate to use a Collection as the return type of a method in a multi-threaded environment. Here is our situation:
    We have four classes -- Widget, WidgetManager, ClientA, and ClientB. ClientA and ClientB are running in different Threads from each other and from the WidgetManager.
    The WidgetManager class that uses a Collection of Widgets internally, and passes the Collection (or an Iterator over it) out as a return value of a method to ClientA, which is running in another thread. ClientA would start to go through it using next() and hasNext() of the Iterator. If the WidgetManager were to get a request from ClientB running in another thread to eliminate a Widget, it would attempt to remove it from the Collection. If ClientA were still looping through the Iterator, this would throw an IllegalStateException b/c the system would be in an inconsistent state. The Iterator given to the ClientA is directly linked to the actual Collection in the WidgetManager (am I right so far?).
    In my opinion, in most cases we don't want to synchronize Collections. In the example above, if we had passed out a synchronized Collection, then the WidgetManager couldn't touch the collection while the client was looping through the Iterator. If the client got hung up while looping, then the WidgetManager would be hung up. In this case, I think that it will be better to use the toArray() method of Collection to just dump out the contents to a plain array of Objects. Actually, the WidgetManager could convert this array of Objects to an array of Widgets before passing it out, which would give us the type checking that we don't get with Containers.
    The condition where you would want to use a synchronized Collection would be when you actually want the client to do some writing or removing from the Collection. I would expect this to be pretty rare since you usually dont want to give clients access to an interal member (the Collection) of a class.
    I think that it is also possible to have read-only Collections, but I think (don't know for sure) that you would still have the same IllegalStateException or synchronization probelms.
    Can someone point out the errors in my thinking? Or should you generally only use Collections as internal members in a multi-threaded environment, and use toArray() whenever you want to pass the Collection's data outside of the class?
    Thanks for any help.
    Keith

    I haven't tested what happens when you synchronize the
    Collection, but I think that you are right. But this
    causes the problem that I mentioned in the first post.
    That is, what happens if your client STARTS running
    through the Iterator, and then stops or gets hung up
    for some reason? I assume that you're still blocked.
    And it's pretty important to me in this case to not
    t be blocked -- WidgetManager is the highest level
    class in the system.
    I'd like to know if anyone has tested this.
    The Iterator implementations used in java.util do not use any synchronization by itself, (which is what you would expect since synchronization over multiple method call will involve much more complications and slower performance) . With iterator, you have to provide the necessary synchronization yourself to maintain thread-safety like this
    Iterator itr = get Iterator from collectionInstance ;
    synchronized(collectionInstance) {
    while(itr.hasNext())
    process itr.next() ...
    As long as your client code gracefully exits the synchronized block on a stop( or hangup, given that it is detected and handled fast enough), it will not be a problem.
    Also, I'd like an example of when you WOULD want to
    return a Collection. I'm specifically interested in
    when you would want to return one in a multi-threaded
    environment, but I'm beginning to wonder when you
    would EVER want to return one from a method.
    Collections are great for internal uses, but you lose
    type-checking and you expose the internals of your
    class to modification when you use them as return
    types. And if you're returning a read-only
    Collection, you might as well return an array, right?Using a read-only proxy will be much faster and space-efficient than toArray().

  • Thread pool rejecting threads when I don't think it should, ideas?

    Hi,
    I have a server application in which I only want a specific number of simultaneous requests. If the server gets more then this number it is suppose to close the connection (sends an HTTP 503 error to the client). To do this I used a fix thread pool. When I start the server and submit the max number of requests I get the expected behavior. However if I resubmit the request (within a small period of time, e.g. 1-15 seconds after the first one) I get very odd behavior in that some of the requests are rejected. For example if I set the max to 100 the first set of requests will work fine (100 requests, 100 responses). I then submit again and a small number will be rejected (I've seen it range from 1 to 15 rejected)....
    I made a small app which kind of duplicates this behavior (see below). Basically when I see is that the first time submitting requests works fine but the second time I get a rejected one. As best as I can tell none should be rejected....
    Here is the code, I welcome your thoughts or if you see something I am doing wrong here...
    <pre>
    import java.util.concurrent.*;
    import java.util.concurrent.atomic.AtomicInteger;
    public class ThreadPoolTest {
         static AtomicInteger count = new AtomicInteger();
         public static class threaded implements Runnable {
              @Override
              public void run() {
                   System.out.println("In thread: " + Thread.currentThread().getId());
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        System.out.println("Thread: " + Thread.currentThread().getId()
                                  + " interuptted");
                   System.out.println("Exiting run: " + Thread.currentThread().getId());
         private static int maxThreads = 3;
         private ThreadPoolExecutor pool;
         public ThreadPoolTest() {
              super();
              pool = new java.util.concurrent.ThreadPoolExecutor(
                        1, maxThreads - 1, 60L, TimeUnit.SECONDS,
                        new ArrayBlockingQueue<Runnable>(1));
         public static void main(String[] args) throws InterruptedException {
              ThreadPoolTest object = new ThreadPoolTest();
              object.doThreads();
              Thread.sleep(3000);
              object.doThreads();
              object.pool.shutdown();
              try {
                   object.pool.awaitTermination(60, TimeUnit.SECONDS);
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         private void doThreads() {
              int submitted = 0, rejected = 0;
              int counter = count.getAndIncrement();
              for (int x = 0; x < maxThreads ; x++) {
                   try {
                        System.out.println("Run #: " + counter + " submitting " + x);
                        pool.execute(new threaded());
                        submitted++;
                   catch (RejectedExecutionException re) {
                        System.err.println("\tRun #: " + counter + ", submission " + x
                                  + " was rejected");
                        System.err.println("\tQueue active: " + pool.getActiveCount());
                        System.err.println("\tQueue size: " + pool.getPoolSize());
                        rejected++;
              System.out.println("\n\n\tRun #: " + counter);
              System.out.println("\tSubmitted: " + (submitted + rejected));
              System.out.println("\tAccepted: " + submitted);
              System.out.println("\tRejected: " + rejected + "\n\n");
    </pre>

    First thank you for taking the time to reply, I do appreciate it.
    jtahlborn - The code provided here is a contrived example trying to emulate the bigger app as best as I could. The actual program doesn't have any sleeps, the sleep in the secondary thread is to simulate the program doing some work & replying to a request. The sleep in the primary thread is to simulate a small delay between 'requests' to the pool. I can make this 1 second and up to (at least) 5 seconds with the same results. Additionally I can take out the sleep in the secondary thread and still see the a rejection.
    EJP - Yes I am aware of the TCP/IP queue, however; I don't see that as relevant to my question. The idea is not to prevent the connection but to respond to the client saying we can't process the request (send an "HTTP 503" error). So basically if we have, say, 100 threads running then the 101st, connection will get a 503 error and the connection will be closed.
    Also my test platform - Windows 7 64bit running Java 1.6.0_24-b07 (32bit) on an Intel core i7.
    It occurred to me that I did not show the output of the test program. As the output shows below, the first set of requests are all processed properly. The second set of requests is not. The pool should have 2 threads and 1 slot in the queue, so by the time the second "request" is made at least 2 of the requests from the first call should be done processing, so I could possibly understand run 1, submit #2 failing but not submit 1.
    <pre>
    Run #: 0 submitting 0
    Run #: 0 submitting 1
    Run #: 0 submitting 2
    In thread: 8
    In thread: 9
    Exiting run: 8
    Exiting run: 9
         Run #: 0
         Submitted: 3
         Accepted: 3
         Rejected: 0
    In thread: 8
    Exiting run: 8
    Run #: 1 submitting 0
    In thread: 9
    Run #: 1 submitting 1
         Run #: 1, submission 1 was rejected
         Queue active: 1
         Queue size: 2
    Run #: 1 submitting 2
         Run #: 1
         Submitted: 3
         Accepted: 2
         Rejected: 1
    In thread: 8
    Exiting run: 9
    Exiting run: 8
    </pre>

Maybe you are looking for