java wait all threads in pool - java

Is there a way to wait all threads in executor pool when pause button pressed and rerun play button pressed? I tried CountDownLatch but I dont know I must put it after executor declaration or in run () method? I dont have much information about threads.please can someone tell me how I can do.Thanks
public static CountDownLatch waiter;
public static ExecutorService pool;
public Action() throws InterruptedException{
pool=Executors.newFixedThreadPool(2);
waiter=new CountDownLatch(2); // to wait
robot1=new Robot(0,560,"rbt1"); // starts random free position
robot2=new Robot(0,560,"rbt2");
if(Frame.pause==false){
pool.submit(robot1);
pool.submit(robot2);}
if(Frame.pause==true){
waiter.await();
}
}

Your Robot worker needs a shared thread-safe way to check whether workers should be paused or playing. In the run() method of your worker, if the thread is paused, wait for notification on this lock object. While looping, or whatever it is the worker does, periodically check the state of the lock, and pause the worker if needed.
pauseIfNeeded() {
synchronized(workerLock) {
if (workerLock.isPaused()) {
workerLock.wait();
}
}
}
Your pause and play button should get a synchronized lock on the workerLock, and set the paused property, and call notify() on the workerLock. This will let the workers pause or continue as needed. The Executor is always "running", regardless of the paused/playing state.
EDIT
You can refactor the above code into its own class, as follows:
public class WorkerPauseManager {
private boolean paused;
public synchronized void pauseIfNeeded() throws InterruptedException {
if (paused) wait();
}
public synchronized void pause() {
this.paused = true;
}
public synchronized void start() {
this.paused = false;
notifyAll();
}
}
Create a single instance of WorkerPauseManager. Pass this instance to all your Robot workers, and keep a reference for the swing pause/play actions to reference. Your worker thread should call pauseIfNeeded.
Here's an SCCE using the WorkerPauseManager:
public class WorkerPauseManagerTest {
public static void main(String[] args) {
final WorkerPauseManager pauseManager = new WorkerPauseManager();
new Worker("Worker 1", pauseManager).start();
new Worker("Worker 2", pauseManager).start();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JToggleButton playPauseButton = new JToggleButton(new AbstractAction("Pause") {
public void actionPerformed(final ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
pauseManager.start();
source.setText("Pause");
} else {
pauseManager.pause();
source.setText("Play");
}
}
});
JOptionPane.showMessageDialog(null, playPauseButton, "WorkerPauseManager Demo", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
});
}
private static class Worker extends Thread {
final String name;
final WorkerPauseManager pauseManager;
public Worker(final String name, final WorkerPauseManager pauseManager) {
this.name = name;
this.pauseManager = pauseManager;
}
#Override
public void run() {
while (!Thread.interrupted()) {
try {
pauseManager.pauseIfNeeded();
System.out.println(name + " is running");
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}

You can wait for all the threads to finish with:
pool.awaitTermination(60, TimeUnit.SECONDS); // hopefully 60 seconds are enough
See: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination%28long,%20java.util.concurrent.TimeUnit%29

Related

IllegalMonitorStateException: object not locked by thread before wait()

I know that there are a lot of similar questions, but no one helped me. I am getting IllegalMonitorStateException: object not locked by thread before wait() when I try to pause the thread.
Here is my initialization method:
// called only once in constructor; the variables are global ( private Thread ... )
public void init() {
recordingThread = new Thread(new Runnable() {
#Override
public void run() {
isNewRecordingThread= false;
record();
}
});
recognitionThread = new Thread(new Runnable() {
#Override
public void run() {
isNewRecognition= false;
recognize();
}
});
...
}
startRecording method:
private synchronized void startRecording(Thread recordingThread) {
if(isNewRecordingThread){
recordingThread.start();
return;
}
recordingThread.notify();
}
startRecognition method:
private synchronized void startRecognition(Thread recognitionThread) {
shouldContinueRecognition = true;
if(isNewRecognition){
recognitionThread.start();
return;
}
recognitionThread.notify();
}
And the stopping method where I actually get the error:
private synchronized void stopRecordingAndRecognition(Thread recordingThread, Thread recognitionThread) {
try{
if (recordingThread != null && recordingThread.isAlive()) {
recordingThread.wait();
}
if (recognitionThread != null && recognitionThread.isAlive()) {
recognitionThread.wait();
}
} catch (InterruptedException e){
Log.d("TESTING","InterruptedException e= "+e);
}
}
"object not locked by thread before wait()"
Think, what object is meant in this message? That very object for which wait() is applied:
recordingThread.wait();
that is, recordingThread.
synchronized void stopRecordingAndRecognition is irrelevant because it locks this object, and not recordingThread.
So, there are 2 solutions:
force methods to synchronize on recordingThread
embed synchronized methods into the class of recordingThread
"The goal is to start thread, pause it and after resume"
Pausing and resuming threads in Java is a bad practice because leads to subtle and hard to debug errors.
The only reliable way to stop/resume some computational process is to split this process into parts, process that parts in a loop, and before the start of processing the next part, checking if processing is allowed.
As an evolution of this approach, each part is formed as a Runnable and is submitted to a single-threaded Executor. Instead of stop and resume the Executor, producer thread(s) simply stop and resume submitting the partial tasks to the executor.
If (some) parts can be processed in parallel, then multithreaded executor can be used, but it requires coordination between submitting particular tasks.
The goal is to start thread, pause it and after resume
Here is a code snippet that I use for suspending and resuming a thread.
public class ThreadStatus {
private boolean paused;
private final String threadName;
private final ReentrantLock lock;
private final Condition condition;
public ThreadStatus (String name) {
threadName = name;
lock = new ReentrantLock();
condition = lock.newCondition();
paused = false;
}
// check for the thread to be paused
public void checkForPause() {
lock.lock();
try {
while (paused) {
condition.await();
}
} catch (InterruptedException ie) {
// interrupted
} finally {
lock.unlock();
}
}
// Pause the thread
public void pause() {
lock.lock();
try {
paused = true;
} finally {
lock.unlock();
}
}
// Resume the thread
public void resume() {
lock.lock();
try {
paused = false;
condition.signalAll();
} finally {
lock.unlock();
}
}
#Override
public String toString() {
return threadName;
}
}
If you need you could implement isStopped() or isRunning() similarly.
final ThreadStatus threadStatus = new ThreadStatus("Thread-A");
In the client code, call threadStatus.checkForPause() at the relevant point. For example, if you have some repeated processings inside a loop, you can do something like -
while (!threadStatus.isStopped()) {
threadStatus.checkForPause();
// do your processing here
}

How to notify a waiting thread without pausing the main one?

I would like my main thread to notify another thread upon a given event, but without pausing itself.
The other thread is an infinite loop, and I need it to wait after each iteration, until the main thread wakes it again.
This seems to rule out the wait/notify pattern as it does pause the thread that calls notify on the shared monitor. I also thought about CyclicBarrier but I do not want the main thread to call Barrier.await, and wait until the other thread calls Barrier.await as well, because it can take a long time...
Any idea ? Thanks !
make the waiting thread like this:
class MyThread extends Thread() {
private volatile boolean go;
public void wakeUpBuddy() {
go=true;
synchronized(this) {
notify();
}
}
public void run() {
while(!interrupted()) {
// some work before wait
synchronized(this) {
while(!go) {
wait();
}
go = false;
}
// some work after release
}
}
}
Then from the main thread call on the instance of MyThread.wakeUpBuddy(); and it will go one pass and wait for another call.
How about using Observer pattern?
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.TimeUnit;
public class Main extends Observable {
public static void main(String... args) {
final MyThread t = new MyThread();
final Main m = new Main();
m.addObserver(t);
// start the thread
t.start();
for (int i = 0; i < 25; i++) {
if (i % 5 == 0) { // event received?
m.setChanged();
m.notifyObservers(i);
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (Exception ex) {
}
}
}
}
class MyThread extends Thread implements Observer {
private boolean wait = true;
#Override
public void run() {
while (true) {
while (wait) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException ex) {
// interrupted
}
}
System.out.println("I am invoked ..");
wait = true;
}
}
#Override
public void update(Observable o, Object arg) {
System.out.println("Update received .. " + arg);
wait = false;
}
}

wait for N-1 out of N threads to end, then issue an instruction for the last thread

So, i apologize for the title. It's quite hard to explain in one sentence what i would like to do if you have no idea on how it is called.
So assume i can only use primitive thread functions (wait, notify, no concurrent package)
The program has 3 threads, all of them are the same and are called by the main thread. They behave normally until one of the three get an exception and so it must wait for the end of the remaining 2 threads in order to start a recovery process.
I was thinking about a static variable but I'm not really sure about it, i would love to keep it as simple as possible.
Each thread starts at the same time.
I don't see any reason why you can't use a static variable like you suggest. Here's how I would do it with an inner class...
private static boolean running = true;
public void test26546397() {
while (true) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
Thread t3 = new Thread(new MyRunnable());
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
running = true;
// Do recovery
}
}
public class MyRunnable implements Runnable {
#Override
public void run() {
while (running) {
try {
// doStuff
} catch (Exception ex) {
running = false;
}
}
}
}
I would of course replace the while (true) with something a little more suitable.
I think you need java.concurrent.CountdownLatch, however if the java.concurrent package is not available to you can code this yourself using Object.wait/notify and synchronized blocks.
The latch can then be decremented in a finally {} on each Thread, this will be run if the Thread completes, or an exception occurs.
Your main program then just needs to wait for count to become 0.
public class StackOverflow26546397 {
static class CountdownLatch {
private int count;
private Object monitor = new Object();
public CountdownLatch(int count) {
this.count = count;
}
public void countDown() {
synchronized (monitor) {
count--;
monitor.notifyAll();
}
}
public void await() throws InterruptedException {
synchronized (monitor) {
while (count > 0) {
monitor.wait();
}
}
}
}
static class Job implements Runnable {
private CountdownLatch latch;
public Job(CountdownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
try {
// do work.
Thread.sleep((long) (Math.random() * 3000d));
} catch (InterruptedException e) {
//
} finally {
latch.countDown();
}
}
}
public static void main(String[] args) throws InterruptedException {
CountdownLatch latch = new CountdownLatch(3);
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
latch.await();
System.out.println("All threads finished");
}
}
Not sure what you are trying to do but this is as simple as I can think of (just native concurrency):
Create a static or shared volatile boolean
private static volatile boolean exceptionOccured=false
Set the above to 'true' when exception occurs:
....}catch(Exception e){
exceptionOccured=true;
}
Check this periodically in you normal thread flow:
if (exceptionOccured)
//enter you synchronized call here
the synchronized method could look something like:
public synchronized void checkAndRecover(){
//decrement a counter or other logic to identify which is the last Thread and then
//perform any recovery logic
}

How can I start, pause and resume my threads? (by extending thread from classes)

Essentially, what I want to do is start all my threads, pause them all, then resume them all, using the multithreading approach. I am just looking for a simple solution to this. I'm not sure if I have to use a timer or what. Right now when I run it, the threads are like being executed in random order (I guess the PC is just randomly picking which ones it wants to run at a certain time).
class ChoppingThread extends Thread
{
public void run()
{
for(int j=40;j!=0;j-=10)
System.out.println("Chopping vegetables...("+j+" seconds left)");
}
}
class MixingThread extends Thread
{
public void run()
{
for(int k=60;k!=0;k-=10)
System.out.println("Mixing sauces...("+k+" seconds left)");
}
}
class TenderizingThread extends Thread
{
public void run()
{
for(int j=50;j!=0;j-=10)
System.out.println("Tenderizing meat...("+j+" seconds left)");
}
}
class MultiThreadTasking
{
public static void main (String [] args)
{
ChoppingThread ct = new ChoppingThread();
MixingThread mt = new MixingThread();
TenderizingThread tt = new TenderizingThread();
System.out.println("\nWelcome to the busy kitchen.");
//putting threads into ready state
ct.start();
mt.start();
tt.start();
}
}
There are probably other ways to achieve the same result, but this is the simplest I can come up with off the top of my head (I know, sad isn't it)...
Basically, this is a special Runnable with some additional management functionality.
This basically contains a state flag that indicates the state of the task and a monitor lock
public class ThreadFun {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
task.pauseTask();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
task.resumeTask();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
task.stopTask();
}
public enum TaskState {
Running,
Stopped,
Paused
}
public static class MyTask implements Runnable {
private static final Object PAUSED_LOCK = new Object();
private volatile TaskState state = TaskState.Running;
public void pauseTask() {
if (state == TaskState.Running) {
System.out.println("Paused...");
state = TaskState.Paused;
}
}
public void resumeTask() {
if (state == TaskState.Paused) {
state = TaskState.Running;
synchronized (PAUSED_LOCK) {
PAUSED_LOCK.notifyAll();
}
System.out.println("Resumed...");
}
}
public void stopTask() {
if (state == TaskState.Running || state == TaskState.Paused) {
state = TaskState.Stopped;
System.out.println("Stopped...");
}
}
public boolean isStopped() {
return state == TaskState.Stopped;
}
public boolean isPaused() {
return state == TaskState.Paused;
}
protected void doPause() {
synchronized (PAUSED_LOCK) {
while (isPaused()) {
try {
PAUSED_LOCK.wait();
} catch (InterruptedException ex) {
}
}
}
}
#Override
public void run() {
int index = 0;
while (!isStopped() && index < 1000) {
try {
Thread.sleep(25);
} catch (InterruptedException ex) {
}
doPause();
index++;
System.out.println(index);
}
stopTask(); // Make sure the task is marked as begin stopped ;)
}
}
}
The main criteria is you will need to pool isStopped and doPause at appropriate points to ensure that they are begin implemented as required...
To coordinate them use a CyclicBarrier.
To launch them all at the same time use a CountDownLatch.
Google the two classes above for many examples and explanations.
To fully understand what is happening read the Java Concurrency In Practice book.
I believe you can accomplish this by using Object.wait and Thread.interrupt.
Object.wait blocks until notify is called. So
private boolean paused;
private Object waitObject;
...
public void run() {
for ... {
if (this.paused) { this.waitObject.wait(); }
...
public void pause() { this.paused = true; }
public void resume() { this.paused = false; this.waitObject.notify(); }
Then you can call pause to pause the thread.
Thread.interrupt can help with stopping.
private boolean paused;
...
public void run() {
for ... {
// interrupted() is different from interrupt()!
if (this.iterrupted()) { break; }
...
To stop it, you would call interrupt() from another thread.
This is the basic idea, but there's a lot of details to worry about here. For example, wait can throw an InterruptedException you'll need to handle. Also, wait is not guaranteed to return only after a notify. It can return randomly. Here is a pair of tutorials:
Wait: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
Interrupt: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

How to thread-safe signal threads to pause in Java

I have a bunch of threads running concurrently. Sometimes a thread needs to notify other threads to wait for it to finish a job and signal them again to resume. Since I'm somehow new to Java's synchronization, I wonder what is the right way to do such thing. My code is something like this:
private void Concurrent() {
if (shouldRun()) {
// notify threads to pause and wait for them
DoJob();
// resume threads
}
// Normal job...
}
Update:
Note that the code I wrote is inside a class which will be executed by each thread. I don't have access to those threads or how they are running. I'm just inside threads.
Update 2:
My code is from a crawler class. The crawler class (crawler4j) knows how to handle concurrency. The only thing I need is to pause other crawlers before running a function and resume them afterwards. This code is the basics of my crawler:
public class TestCrawler extends WebCrawler {
private SingleThread()
{
//When this function is running, no other crawler should do anything
}
#Override
public void visit(Page page) {
if(SomeCriteria())
{
//make all other crawlers stop until I finish
SingleThread();
//let them resume
}
//Normal Stuff
}
}
Here is a short example on how to achieve this with the cool java concurrency stuff:
snip old code doesn't matter anymore with the Pause class.
EDIT:
Here is the new Test class:
package de.hotware.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
private Pause mPause;
public Test() {
this.mPause = new Pause();
}
public void concurrent() throws InterruptedException {
while(true) {
this.mPause.probe();
System.out.println("concurrent");
Thread.sleep(100);
}
}
public void crucial() throws InterruptedException {
int i = 0;
while (true) {
if (i++ % 2 == 0) {
this.mPause.pause(true);
System.out.println("crucial: exclusive execution");
this.mPause.pause(false);
} else {
System.out.println("crucial: normal execution");
Thread.sleep(1000);
}
}
}
public static void main(String[] args) {
final Test test = new Test();
Runnable run = new Runnable() {
#Override
public void run() {
try {
test.concurrent();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable cruc = new Runnable() {
#Override
public void run() {
try {
test.crucial();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
ExecutorService serv = Executors.newCachedThreadPool();
serv.execute(run);
serv.execute(run);
serv.execute(cruc);
}
}
And the utility Pause class:
package de.hotware.test;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Utility class to pause and unpause threads
* with Java Concurrency
* #author Martin Braun
*/
public class Pause {
private Lock mLock;
private Condition mCondition;
private AtomicBoolean mAwait;
public Pause() {
this.mLock = new ReentrantLock();
this.mCondition = this.mLock.newCondition();
this.mAwait = new AtomicBoolean(false);
}
/**
* waits until the threads until this.mAwait is set to true
* #throws InterruptedException
*/
public void probe() throws InterruptedException {
while(this.mAwait.get()) {
this.mLock.lock();
try {
this.mCondition.await();
} finally {
this.mLock.unlock();
}
}
}
/**
* pauses or unpauses
*/
public void pause(boolean pValue) {
if(!pValue){
this.mLock.lock();
try {
this.mCondition.signalAll();
} finally {
this.mLock.unlock();
}
}
this.mAwait.set(pValue);
}
}
The basic usage is to call probe() before each run. This will block if it is paused until pause(false) is called.
Your class would look like this:
public class TestCrawler extends WebCrawler {
private Pause mPause;
public TestCrawler(Pause pPause) {
this.mPause = pPause;
}
private SingleThread()
{
//When this function is running, no other crawler should do anything
}
#Override
public void visit(Page page) {
if(SomeCriteria())
{
//only enter the crucial part once if it has to be exclusive
this.mPause.probe();
//make all other crawlers stop until I finish
this.mPause.pause(true);
SingleThread();
//let them resume
this.mPause.pause(false);
}
this.mPause.probe();
//Normal Stuff
}
}
public class StockMonitor extends Thread {
private boolean suspend = false;
private volatile Thread thread;
public StockMonitor() {
thread = this;
}
// Use name with underscore, in order to avoid naming crashing with
// Thread's.
private synchronized void _wait() throws InterruptedException {
while (suspend) {
wait();
}
}
// Use name with underscore, in order to avoid naming crashing with
// Thread's.
public synchronized void _resume() {
suspend = false;
notify();
}
// Use name with underscore, in order to avoid naming crashing with
// Thread's.
public synchronized void _suspend() {
suspend = true;
}
public void _stop() {
thread = null;
// Wake up from sleep.
interrupt();
}
#Override
public void run() {
final Thread thisThread = Thread.currentThread();
while (thisThread == thread) {
_wait();
// Do whatever you want right here.
}
}
}
Calling _resume and _suspend will enable you to resume and pause the Thread. _stop will let you stop the thread gracefully. Note that, once you stop the Thread, there is no way to resume it again. The Thread is no longer usable.
The code is being picked from a real world open source project : http://jstock.hg.sourceforge.net/hgweb/jstock/jstock/file/b17c0fbfe37c/src/org/yccheok/jstock/engine/RealTimeStockMonitor.java#l247
You can use wait() and notify()
thread waiting:
// define mutex as field
Object mutex = new Object();
// later:
synchronized(mutex) {
wait();
}
notify the thread to continue
synchronized (mutex) {
notify();
}

Categories