Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #29192 > unrolled thread

thread pool

Started byPhilipp Kraus <philipp.kraus@flashpixx.de>
First post2014-07-22 15:00 +0200
Last post2014-07-24 20:50 -0700
Articles 14 — 3 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-22 15:00 +0200
    Re: thread pool Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-07-22 09:11 -0400
      Re: thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-22 16:32 +0200
      Re: thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-22 21:38 +0200
        Re: thread pool Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-07-22 16:29 -0400
          Re: thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-22 23:01 +0200
            Re: thread pool Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-07-22 17:14 -0400
              Re: thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-23 08:11 +0200
                Re: thread pool Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-07-23 07:24 -0400
                  Re: thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-23 15:57 +0200
                    Re: thread pool Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-07-23 11:41 -0400
                      Re: thread pool Philipp Kraus <philipp.kraus@flashpixx.de> - 2014-07-24 09:55 +0200
                        Re: thread pool Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-07-24 08:39 -0400
    Re: thread pool Kevin McMurtrie <mcmurtrie@pixelmemory.us> - 2014-07-24 20:50 -0700

#29192 — thread pool

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-22 15:00 +0200
Subjectthread pool
Message-ID<lqlna0$23fm$1@ariadne.rz.tu-clausthal.de>
Hello,

I would like to create a thread pool with threads, which are should 
stopped by the user.
So I create my pool with

        m_pool = Executors.newCachedThreadPool();
        for (int i = 0; i < m_barrier.getParties(); i++)
            m_pool.submit(new Worker(m_barrier));

my Worker implements Runnable with the run-method

while (!Thread.currentThread().isInterrupted()) {
     // do something
}

Within the while-loop I run my barrier and I catch the InterruptedException

I would like to create a thread pool with a number of threads, which 
runs until the user
sends a stop signal. At the moment I run m_pool.shutdown() and/or 
shutdownNow(), but
which way is the correct Java structure. My target is, that a method 
creates all threads
of the pool, each thread runs unlimited time until the user sends a 
stop signal.

Thanks a lot

Phil

[toc] | [next] | [standalone]


#29195

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-07-22 09:11 -0400
Message-ID<lqlntl$gcc$1@dont-email.me>
In reply to#29192
On 7/22/2014 9:00 AM, Philipp Kraus wrote:
> Hello,
>
> I would like to create a thread pool with threads, which are should
> stopped by the user.
> So I create my pool with
>
>         m_pool = Executors.newCachedThreadPool();
>         for (int i = 0; i < m_barrier.getParties(); i++)
>             m_pool.submit(new Worker(m_barrier));
>
> my Worker implements Runnable with the run-method
>
> while (!Thread.currentThread().isInterrupted()) {
>      // do something
> }
>
> Within the while-loop I run my barrier and I catch the InterruptedException
>
> I would like to create a thread pool with a number of threads, which
> runs until the user
> sends a stop signal. At the moment I run m_pool.shutdown() and/or
> shutdownNow(), but
> which way is the correct Java structure. My target is, that a method
> creates all threads
> of the pool, each thread runs unlimited time until the user sends a stop
> signal.

     If "each thread runs unlimited time," why use a thread pool?  The
purpose of this kind of pool is to run many short-lived (usually) tasks
on a set of threads, with each thread handling many tasks in succession.
You don't need that (it seems), so wouldn't it be simpler to launch
as many threads as you want and just let them run?  When it's time to
stop you can interrupt them all (telling them to quit) and join them
all (so you'll know when all the quitting's finished).

     If that doesn't seem to meet your need, please describe what you're
trying to do in more detail.

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29198

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-22 16:32 +0200
Message-ID<lqlsl9$24mq$1@ariadne.rz.tu-clausthal.de>
In reply to#29195
On 2014-07-22 13:11:14 +0000, Eric Sosman said:

> On 7/22/2014 9:00 AM, Philipp Kraus wrote:
>> Hello,
>> 
>> I would like to create a thread pool with threads, which are should
>> stopped by the user.
>> So I create my pool with
>> 
>> m_pool = Executors.newCachedThreadPool();
>> for (int i = 0; i < m_barrier.getParties(); i++)
>> m_pool.submit(new Worker(m_barrier));
>> 
>> my Worker implements Runnable with the run-method
>> 
>> while (!Thread.currentThread().isInterrupted()) {
>> // do something
>> }
>> 
>> Within the while-loop I run my barrier and I catch the InterruptedException
>> 
>> I would like to create a thread pool with a number of threads, which
>> runs until the user
>> sends a stop signal. At the moment I run m_pool.shutdown() and/or
>> shutdownNow(), but
>> which way is the correct Java structure. My target is, that a method
>> creates all threads
>> of the pool, each thread runs unlimited time until the user sends a stop
>> signal.
> 
>      If "each thread runs unlimited time," why use a thread pool?  The
> purpose of this kind of pool is to run many short-lived (usually) tasks
> on a set of threads, with each thread handling many tasks in succession.
> You don't need that (it seems), so wouldn't it be simpler to launch
> as many threads as you want and just let them run?  When it's time to
> stop you can interrupt them all (telling them to quit) and join them
> all (so you'll know when all the quitting's finished).
> 
>      If that doesn't seem to meet your need, please describe what you're
> trying to do in more detail.

Greate this seems to be easier.

Phil

[toc] | [prev] | [next] | [standalone]


#29206

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-22 21:38 +0200
Message-ID<lqmekf$mh1$1@online.de>
In reply to#29195
On 2014-07-22 13:11:14 +0000, Eric Sosman said:

> On 7/22/2014 9:00 AM, Philipp Kraus wrote:
>> Hello,
>> 
>> I would like to create a thread pool with threads, which are should
>> stopped by the user.
>> So I create my pool with
>> 
>> m_pool = Executors.newCachedThreadPool();
>> for (int i = 0; i < m_barrier.getParties(); i++)
>> m_pool.submit(new Worker(m_barrier));
>> 
>> my Worker implements Runnable with the run-method
>> 
>> while (!Thread.currentThread().isInterrupted()) {
>> // do something
>> }
>> 
>> Within the while-loop I run my barrier and I catch the InterruptedException
>> 
>> I would like to create a thread pool with a number of threads, which
>> runs until the user
>> sends a stop signal. At the moment I run m_pool.shutdown() and/or
>> shutdownNow(), but
>> which way is the correct Java structure. My target is, that a method
>> creates all threads
>> of the pool, each thread runs unlimited time until the user sends a stop
>> signal.
> 
>      If "each thread runs unlimited time," why use a thread pool?  The
> purpose of this kind of pool is to run many short-lived (usually) tasks
> on a set of threads, with each thread handling many tasks in succession.
> You don't need that (it seems), so wouldn't it be simpler to launch
> as many threads as you want and just let them run?  When it's time to
> stop you can interrupt them all (telling them to quit) and join them
> all (so you'll know when all the quitting's finished).
> 
>      If that doesn't seem to meet your need, please describe what you're
> trying to do in more detail.

This works very fast :-) but I have got a problem with the thread interrupt.
I create a thread pool with:

 m_threadcounter = new CountDownLatch(m_barrier.getParties());
for (int i = 0; i < m_barrier.getParties(); i++)
	new CWorker(m_runners, m_threadcounter, m_barrier, i == 0, m_world, 
m_currentstep).start();

and stop the pool with:

        try {

            m_runners.interrupt();
            m_threadcounter.await();

        } catch (InterruptedException l_exception) {
            m_Logger.error(l_exception.getMessage());
        }

m_runners is a ThreadGroup;

The thread run shows:

 while (!Thread.currentThread().isInterrupted()) {

           // do something

            try {
                
Thread.sleep(CConfiguration.getInstance().get().ThreadSleepTime);
            } catch (InterruptedException l_exception) {
                Thread.currentThread().interrupt();
            }

        }

        m_counter.countDown();

This works fine on the first run. After I run the stop part once and 
run the creation part again
all new threads a stopped, because the interrupt flag is set, so my new 
thread dows not run the while
loop within the run.

So I would like to create a a thread group, run it, stop it and create 
a group again. I cannot set the thread to
sleep, because the data which is used by the threads must be 
reinitialize if the group is created

Thanks a lot

Phil

[toc] | [prev] | [next] | [standalone]


#29207

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-07-22 16:29 -0400
Message-ID<lqmhk2$pnm$1@dont-email.me>
In reply to#29206
On 7/22/2014 3:38 PM, Philipp Kraus wrote:
> On 2014-07-22 13:11:14 +0000, Eric Sosman said:
>
>> On 7/22/2014 9:00 AM, Philipp Kraus wrote:
>>> Hello,
>>>
>>> I would like to create a thread pool with threads, which are should
>>> stopped by the user.
>>> So I create my pool with
>>>
>>> m_pool = Executors.newCachedThreadPool();
>>> for (int i = 0; i < m_barrier.getParties(); i++)
>>> m_pool.submit(new Worker(m_barrier));
>>>
>>> my Worker implements Runnable with the run-method
>>>
>>> while (!Thread.currentThread().isInterrupted()) {
>>> // do something
>>> }
>>>
>>> Within the while-loop I run my barrier and I catch the
>>> InterruptedException
>>>
>>> I would like to create a thread pool with a number of threads, which
>>> runs until the user
>>> sends a stop signal. At the moment I run m_pool.shutdown() and/or
>>> shutdownNow(), but
>>> which way is the correct Java structure. My target is, that a method
>>> creates all threads
>>> of the pool, each thread runs unlimited time until the user sends a stop
>>> signal.
>>
>>      If "each thread runs unlimited time," why use a thread pool?  The
>> purpose of this kind of pool is to run many short-lived (usually) tasks
>> on a set of threads, with each thread handling many tasks in succession.
>> You don't need that (it seems), so wouldn't it be simpler to launch
>> as many threads as you want and just let them run?  When it's time to
>> stop you can interrupt them all (telling them to quit) and join them
>> all (so you'll know when all the quitting's finished).
>>
>>      If that doesn't seem to meet your need, please describe what you're
>> trying to do in more detail.
>
> This works very fast :-) but I have got a problem with the thread
> interrupt.
> I create a thread pool with:
>
> m_threadcounter = new CountDownLatch(m_barrier.getParties());
> for (int i = 0; i < m_barrier.getParties(); i++)
>      new CWorker(m_runners, m_threadcounter, m_barrier, i == 0, m_world,
> m_currentstep).start();
>
> and stop the pool with:
>
>         try {
>
>             m_runners.interrupt();
>             m_threadcounter.await();
>
>         } catch (InterruptedException l_exception) {
>             m_Logger.error(l_exception.getMessage());
>         }
>
> m_runners is a ThreadGroup;
>
> The thread run shows:
>
> while (!Thread.currentThread().isInterrupted()) {
>
>            // do something
>
>             try {
> Thread.sleep(CConfiguration.getInstance().get().ThreadSleepTime);
>             } catch (InterruptedException l_exception) {
>                 Thread.currentThread().interrupt();
>             }
>
>         }
>
>         m_counter.countDown();
>
> This works fine on the first run. After I run the stop part once and run
> the creation part again
> all new threads a stopped, because the interrupt flag is set, so my new
> thread dows not run the while
> loop within the run.
>
> So I would like to create a a thread group, run it, stop it and create a
> group again. I cannot set the thread to
> sleep, because the data which is used by the threads must be
> reinitialize if the group is created

     The normal pattern is for the interrupted Thread to terminate,
either by returning from its run() method (or its Runnable's run()
method) or by throwing an uncaught Exception (InterruptedException,
for example).  The control thread can call join() on the terminating
workers to learn when they've all stopped.  Then to start anew you'd
create a new batch of worker Threads, and all of them would go through
whatever initialization you like.

     Here's one way to arrange things (there are many others), just
typed in without testing:

	class Worker implements Runnable {
	    ...
	    public void run() {
	        try {
	            for(;;) {
	                // do something
	                Thread.sleep(interval);
	            }
	        } catch (InterruptedException ex) {
	            // Stop running, but otherwise ignore
	        }
	    }
	    ...
	}

	class Master {
	    ...
	    private List<Thread> threads = new ArrayList<>();
	    ...
	    void startThreads(int howMany) {
	        while (--howMany >= 0) {
	            Thread t = new Thread(new Worker());
	            t.start();
	            threads.add(t);
	        }
	    }
	    ...
	    void stopThreads() {
	        // Tell all the workers to stop:
	        for (Thread t : threads) {
	            t.interrupt();
	        }
	        // Wait until they have all done so:
	        for (Thread t : threads) {
	            try {
	                t.join();
	            } catch (InterruptedException ex) {
	                // The *Master* has been interrupted -- this may
	                // be reason to panic, log a failure message,
	                // and shut down the whole application
	            }
	        }
	        threads.clear();  // All the old Threads are gone.
	    }
	    ...
	}

     I've never used ThreadGroup, so I can't offer advice on it.  (Java
may be using ThreadGroup behind the scenes when I operate on Threads and
Executors and so on, but I've never had a reason to use ThreadGroup
directly.)

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29208

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-22 23:01 +0200
Message-ID<lqmjf2$656$1@online.de>
In reply to#29207

[Multipart message — attachments visible in raw view] — view raw

On 2014-07-22 20:29:51 +0000, Eric Sosman said:

> On 7/22/2014 3:38 PM, Philipp Kraus wrote:
>> On 2014-07-22 13:11:14 +0000, Eric Sosman said:
>> 
>>> On 7/22/2014 9:00 AM, Philipp Kraus wrote:
>>>> Hello,
>>>> 
>>>> I would like to create a thread pool with threads, which are should
>>>> stopped by the user.
>>>> So I create my pool with
>>>> 
>>>> m_pool = Executors.newCachedThreadPool();
>>>> for (int i = 0; i < m_barrier.getParties(); i++)
>>>> m_pool.submit(new Worker(m_barrier));
>>>> 
>>>> my Worker implements Runnable with the run-method
>>>> 
>>>> while (!Thread.currentThread().isInterrupted()) {
>>>> // do something
>>>> }
>>>> 
>>>> Within the while-loop I run my barrier and I catch the
>>>> InterruptedException
>>>> 
>>>> I would like to create a thread pool with a number of threads, which
>>>> runs until the user
>>>> sends a stop signal. At the moment I run m_pool.shutdown() and/or
>>>> shutdownNow(), but
>>>> which way is the correct Java structure. My target is, that a method
>>>> creates all threads
>>>> of the pool, each thread runs unlimited time until the user sends a stop
>>>> signal.
>>> 
>>> If "each thread runs unlimited time," why use a thread pool?  The
>>> purpose of this kind of pool is to run many short-lived (usually) tasks
>>> on a set of threads, with each thread handling many tasks in succession.
>>> You don't need that (it seems), so wouldn't it be simpler to launch
>>> as many threads as you want and just let them run?  When it's time to
>>> stop you can interrupt them all (telling them to quit) and join them
>>> all (so you'll know when all the quitting's finished).
>>> 
>>> If that doesn't seem to meet your need, please describe what you're
>>> trying to do in more detail.
>> 
>> This works very fast :-) but I have got a problem with the thread
>> interrupt.
>> I create a thread pool with:
>> 
>> m_threadcounter = new CountDownLatch(m_barrier.getParties());
>> for (int i = 0; i < m_barrier.getParties(); i++)
>> new CWorker(m_runners, m_threadcounter, m_barrier, i == 0, m_world,
>> m_currentstep).start();
>> 
>> and stop the pool with:
>> 
>> try {
>> 
>> m_runners.interrupt();
>> m_threadcounter.await();
>> 
>> } catch (InterruptedException l_exception) {
>> m_Logger.error(l_exception.getMessage());
>> }
>> 
>> m_runners is a ThreadGroup;
>> 
>> The thread run shows:
>> 
>> while (!Thread.currentThread().isInterrupted()) {
>> 
>> // do something
>> 
>> try {
>> Thread.sleep(CConfiguration.getInstance().get().ThreadSleepTime);
>> } catch (InterruptedException l_exception) {
>> Thread.currentThread().interrupt();
>> }
>> 
>> }
>> 
>> m_counter.countDown();
>> 
>> This works fine on the first run. After I run the stop part once and run
>> the creation part again
>> all new threads a stopped, because the interrupt flag is set, so my new
>> thread dows not run the while
>> loop within the run.
>> 
>> So I would like to create a a thread group, run it, stop it and create a
>> group again. I cannot set the thread to
>> sleep, because the data which is used by the threads must be
>> reinitialize if the group is created
> 
>      The normal pattern is for the interrupted Thread to terminate,
> either by returning from its run() method (or its Runnable's run()
> method) or by throwing an uncaught Exception (InterruptedException,
> for example).  The control thread can call join() on the terminating
> workers to learn when they've all stopped.  Then to start anew you'd
> create a new batch of worker Threads, and all of them would go through
> whatever initialization you like.
> 
>      Here's one way to arrange things (there are many others), just
> typed in without testing:
> 
> 	class Worker implements Runnable {
> 	    ...
> 	    public void run() {
> 	        try {
> 	            for(;;) {
> 	                // do something
> 	                Thread.sleep(interval);
> 	            }
> 	        } catch (InterruptedException ex) {
> 	            // Stop running, but otherwise ignore
> 	        }
> 	    }
> 	    ...
> 	}
> 
> 	class Master {
> 	    ...
> 	    private List<Thread> threads = new ArrayList<>();
> 	    ...
> 	    void startThreads(int howMany) {
> 	        while (--howMany >= 0) {
> 	            Thread t = new Thread(new Worker());
> 	            t.start();
> 	            threads.add(t);
> 	        }
> 	    }
> 	    ...
> 	    void stopThreads() {
> 	        // Tell all the workers to stop:
> 	        for (Thread t : threads) {
> 	            t.interrupt();
> 	        }
> 	        // Wait until they have all done so:
> 	        for (Thread t : threads) {
> 	            try {
> 	                t.join();
> 	            } catch (InterruptedException ex) {
> 	                // The *Master* has been interrupted -- this may
> 	                // be reason to panic, log a failure message,
> 	                // and shut down the whole application
> 	            }
> 	        }
> 	        threads.clear();  // All the old Threads are gone.
> 	    }
> 	    ...
> 	}
> 
>      I've never used ThreadGroup, so I can't offer advice on it.  (Java
> may be using ThreadGroup behind the scenes when I operate on Threads and
> Executors and so on, but I've never had a reason to use ThreadGroup
> directly.)

My solution seems to be similar, but if I run your startThreads again 
the  t.start();
throws the InterruptedException directly, so I do

main()
{
	Master x = new Master();

	x.startThreads(5);
	x.stopThreads();
	x.startThreads(5); <= this does not work because the exception is thrown
}

Phil

[toc] | [prev] | [next] | [standalone]


#29209

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-07-22 17:14 -0400
Message-ID<lqmk8d$e3m$1@dont-email.me>
In reply to#29208
On 7/22/2014 5:01 PM, Philipp Kraus wrote:
>[... ugly double-spaced Googlejunk snipped ...]
> My solution seems to be similar, but if I run your startThreads again
> thet.start();
>
> throws the InterruptedException directly, so I do
>
> main()
> {
> Master x = new Master();
>
> x.startThreads(5);
> x.stopThreads();
> x.startThreads(5); <= this does not work because the exception is thrown
> }

     Are you sure startThreads() is creating and starting brand-
new Threads each time it's called, not re-using old Threads?
To put it another way, are you sure stopThreads() actually stops
all the old Threads and waits for them to finish stopping (and
then clears its "running workers" list)?

     I cannot imagine how a newly-created Thread would find itself
in the interrupted state before anything interrupts it.  Is there
some other part of your program that interrupts Threads when it
shouldn't?

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29220

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-23 08:11 +0200
Message-ID<lqnjln$2l6e$1@ariadne.rz.tu-clausthal.de>
In reply to#29209

[Multipart message — attachments visible in raw view] — view raw

On 2014-07-22 21:14:49 +0000, Eric Sosman said:

> On 7/22/2014 5:01 PM, Philipp Kraus wrote:
>> [... ugly double-spaced Googlejunk snipped ...]
>> My solution seems to be similar, but if I run your startThreads again
>> thet.start();
>> 
>> throws the InterruptedException directly, so I do
>> 
>> main()
>> {
>> Master x = new Master();
>> 
>> x.startThreads(5);
>> x.stopThreads();
>> x.startThreads(5); <= this does not work because the exception is thrown
>> }
> 
>      Are you sure startThreads() is creating and starting brand-
> new Threads each time it's called, not re-using old Threads?
> To put it another way, are you sure stopThreads() actually stops
> all the old Threads and waits for them to finish stopping (and
> then clears its "running workers" list)?

IMHO I do this (m_runners is the threadgroup):

        m_runners.interrupt();
        try {

            m_threadcounter.await();

        } catch (InterruptedException l_exception) {
            m_Logger.error(l_exception.getMessage());
        }

m_threadcounter is the CountDownLatch which is initialize on the 
startThreads with the number of threads and each thread
calls the countDown() method before the run is released

>      I cannot imagine how a newly-created Thread would find itself
> in the interrupted state before anything interrupts it.  Is there
> some other part of your program that interrupts Threads when it
> shouldn't?

I don't think so. The threads are stopped / started from the UI and I 
use some external libraries.

I have build a short example under 
https://github.com/flashpixx/threadtest which shows the problem (I use 
Java 1.8).
I get 
CSimulation@5cad8086		simulation is started with [5] threads
CWorker@18a5eea9		thread [9] starts working
CWorker@3d9bc497		thread [10] starts working
CWorker@7351b7d5		thread [11] starts working
CWorker@6605d308		thread [12] starts working
CWorker@6826907c		thread [13] starts working

CWorker@6605d308		thread [12] stops working with current count down latch [3]
CWorker@18a5eea9		thread [9] stops working with current count down latch [3]
CWorker@7351b7d5		thread [11] stops working with current count down latch [2]
CSimulation@5cad8086		threads stopped
CWorker@3d9bc497		thread [10] stops working with current count down latch [0]
CWorker@6826907c		thread [13] stops working with current count down latch [1]
CSimulation@5cad8086		simulation is stopped




CSimulation@5cad8086		simulation is started with [5] threads
CWorker@b7127ff			thread [14] starts working
CWorker@6441c612		thread [15] starts working
CWorker@67d26a8e		thread [16] starts working
CWorker@193fa958		thread [17] starts working
CWorker@3aa2722f		thread [18] starts working

CWorker@6441c612		thread [15] stops working with current count down latch [3]
CWorker@193fa958		thread [17] stops working with current count down latch [1]
CWorker@3aa2722f		thread [18] stops working with current count down latch [0]
CSimulation@5cad8086		threads stopped
CWorker@67d26a8e		thread [16] stops working with current count down latch [3]
CSimulation@5cad8086		simulation is stopped
CWorker@b7127ff			thread [14] stops working with current count down latch [0]

It seems, that the CountDownLatch does not work as expected. Any idea?

Phil

[toc] | [prev] | [next] | [standalone]


#29225

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-07-23 07:24 -0400
Message-ID<lqo61b$dao$1@dont-email.me>
In reply to#29220
On 7/23/2014 2:11 AM, Philipp Kraus wrote:
> [...]
> It seems, that the CountDownLatch does not work as expected. Any idea?

     Time for an SSCCE, I think. <http://sscce.org/>

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29234

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-23 15:57 +0200
Message-ID<lqof0k$2res$1@ariadne.rz.tu-clausthal.de>
In reply to#29225

[Multipart message — attachments visible in raw view] — view raw

On 2014-07-23 11:24:24 +0000, Eric Sosman said:

> On 7/23/2014 2:11 AM, Philipp Kraus wrote:
>> [...]
>> It seems, that the CountDownLatch does not work as expected. Any idea?
> 
>      Time for an SSCCE, I think. <http://sscce.org/>

see the link https://github.com/flashpixx/threadtest (working example)

Phil

[toc] | [prev] | [next] | [standalone]


#29236

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-07-23 11:41 -0400
Message-ID<lqol2t$tba$1@dont-email.me>
In reply to#29234
On 7/23/2014 9:57 AM, Philipp Kraus wrote:
> On 2014-07-23 11:24:24 +0000, Eric Sosman said:
>
>
> On 7/23/2014 2:11 AM, Philipp Kraus wrote:
>
> [...]
>
> It seems, that the CountDownLatch does not work as expected. Any idea?
>
>
> Time for an SSCCE, I think. <http://sscce.org/>
>
>
> see the link https://github.com/flashpixx/threadtest (working example)

     The meaning of the first "S" seems to have eluded you ...

     I'm not going to plow through all that stuff in detail, and
(as I wrote earlier) I'm unfamiliar with ThreadGroup.  At a glance,
though, it looks like you've got bits and pieces of at least two
different synchronization schemes, perhaps more, all mixed together:
there's a CountDownLatch *and* a CyclicBarrier *and* an AtomicInteger
*and* a bunch of synchronized methods *and* the aforementioned
ThreadGroup, ...  Perhaps you've been trying to achieve parallelism
by adding more and more stuff, but it's my experience that going in
the opposite direction is more fruitful.  An American philosopher
urged us to "Simplify, simplify!" -- in an age before computers, yet
I find his advice essential to success in parallel computing.

     One thing I noticed, though I haven't analyzed things carefully
enough to be sure: You initialize the CountDownLatch with a count
of five, but six different threads call await() on it.  Surely
that can't be right, can it?


-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29262

FromPhilipp Kraus <philipp.kraus@flashpixx.de>
Date2014-07-24 09:55 +0200
Message-ID<lqqe64$mq8$1@ariadne.rz.tu-clausthal.de>
In reply to#29236
On 2014-07-23 15:41:13 +0000, Eric Sosman said:

> On 7/23/2014 9:57 AM, Philipp Kraus wrote:
>> On 2014-07-23 11:24:24 +0000, Eric Sosman said:
>> 
>> 
>> On 7/23/2014 2:11 AM, Philipp Kraus wrote:
>> 
>> [...]
>> 
>> It seems, that the CountDownLatch does not work as expected. Any idea?
>> 
>> 
>> Time for an SSCCE, I think. <http://sscce.org/>
>> 
>> 
>> see the link https://github.com/flashpixx/threadtest (working example)
> 
>      One thing I noticed, though I haven't analyzed things carefully
> enough to be sure: You initialize the CountDownLatch with a count
> of five, but six different threads call await() on it.  Surely
> that can't be right, can it?

5 Threads are running (i=0 to i < 5), so the threads are [0..4] = 5 and 
the await ist
called from outside (another thread). If you increment the number of 
the CountDownLatch
the system will hang up

Phil

[toc] | [prev] | [next] | [standalone]


#29268

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-07-24 08:39 -0400
Message-ID<lqqupv$ah9$1@dont-email.me>
In reply to#29262
On 7/24/2014 3:55 AM, Philipp Kraus wrote:
> On 2014-07-23 15:41:13 +0000, Eric Sosman said:
>
>> On 7/23/2014 9:57 AM, Philipp Kraus wrote:
>>>[...]
>>> see the link https://github.com/flashpixx/threadtest (working example)
>>
>>      One thing I noticed, though I haven't analyzed things carefully
>> enough to be sure: You initialize the CountDownLatch with a count
>> of five, but six different threads call await() on it.  Surely
>> that can't be right, can it?
>
> 5 Threads are running (i=0 to i < 5), so the threads are [0..4] = 5 and
> the await ist
> called from outside (another thread). If you increment the number of the
> CountDownLatch
> the system will hang up

     "Surely I can't be right, can I?"  ;)

     I misread your code: The CSimulation calls await() on the
CountDownLatch, but each CWorker calls await() on a CyclicBarrier
(and calls countDown() on the CountDownLatch).  So in fact only
one thread, not six (or five) calls await() on the CountDownLatch.

     It's still a mystery to me what the CyclicBarrier is for: It
doesn't appear to serve any useful purpose.  It will ensure that
each CWorker finishes the current "step" before moving on to the
next, but (for example) it doesn't guarantee that they'll all see
the same value of m_currentstep.

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29292

FromKevin McMurtrie <mcmurtrie@pixelmemory.us>
Date2014-07-24 20:50 -0700
Message-ID<mcmurtrie-7125E3.20501524072014@news.sonic.net>
In reply to#29192
In article <lqlna0$23fm$1@ariadne.rz.tu-clausthal.de>,
 Philipp Kraus <philipp.kraus@flashpixx.de> wrote:

> Hello,
> 
> I would like to create a thread pool with threads, which are should 
> stopped by the user.
> So I create my pool with
> 
>         m_pool = Executors.newCachedThreadPool();
>         for (int i = 0; i < m_barrier.getParties(); i++)
>             m_pool.submit(new Worker(m_barrier));
> 
> my Worker implements Runnable with the run-method
> 
> while (!Thread.currentThread().isInterrupted()) {
>      // do something
> }
> 
> Within the while-loop I run my barrier and I catch the InterruptedException
> 
> I would like to create a thread pool with a number of threads, which 
> runs until the user
> sends a stop signal. At the moment I run m_pool.shutdown() and/or 
> shutdownNow(), but
> which way is the correct Java structure. My target is, that a method 
> creates all threads
> of the pool, each thread runs unlimited time until the user sends a 
> stop signal.
> 
> Thanks a lot
> 
> Phil

Executors are used to run a fluctuating number of tasks with some stable 
number of threads.  It's not meant for the way you're using it.  Just 
create real Threads (or Runnable for real Threads).



public class ThreadFooCPUIntensive
{
   volatile WorkerFoo threads[]= null;
   
   public synchronized void  start ()
   {
      if (threads == null)
      {
         threads= new WorkerFoo[5];
         for (int i= 0; i < threads.length; ++i)
            threads[i]= new WorkerFoo();
         for (int i= 0; i < threads.length; ++i)
            threads[i].start();
      }
   }
   
   public void stop () throws InterruptedException
   {
      final Thread origThreads[];
      synchronized (this)
      {
         origThreads= threads;
         threads= null;
      }
      
      if (origThreads != null)
         for (int i= 0; i < origThreads.length; ++i)
            origThreads[i].join();
   }
   
   class WorkerFoo extends Thread
   {
      @Override
      public void run()
      {
         final WorkerFoo origThreads[]= threads;
         while (origThreads == threads)
         {
            //CPU intensive stuff
         }
      }
   }
}


--------------- or ------------------------


public class ThreadFooIOIntensive
{
  WorkerFoo threads[]= null;
   
   public synchronized void start ()
   {
      if (threads == null)
      {
         threads= new WorkerFoo[5];
         for (int i= 0; i < threads.length; ++i)
            threads[i]= new WorkerFoo();
         for (int i= 0; i < threads.length; ++i)
            threads[i].start();
      }
   }
   
   public void stop () throws InterruptedException
   {
      final Thread origThreads[];
      synchronized (this)
      {
         origThreads = threads;
         threads = null;
      }

      if (origThreads != null)
      {
         for (int i = 0; i < origThreads.length; ++i)
            origThreads[i].interrupt();
         for (int i = 0; i < origThreads.length; ++i)
            origThreads[i].join();
      }
   }
   
   class WorkerFoo extends Thread
   {
      @Override
      public void run()
      {
         try
         {
            while (true)
            {
               //IO intensive stuff
            }
         }
         catch (InterruptedIOException e)
         {
         }
         catch (InterruptedException e)
         {
         }
      }
   }
}

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web