first what i am trying to do:
During the main thread execution i want to pause the main thread and start two parallel threads. As soon as both this parallel threads terminate, i'd like to start again with the main thread.
What i tried:
...
...
main thread is executing
...
...
CyclicBarrier barrier = new CyclicBarrier(2);
Thread child1 = new Thread(new ThreadBuilderTask(barrier,0));
Thread child2 = new Thread(new ThreadBuilderTask(barrier,1));
child1.start();
child2.start();
/* Now i'm expecting that child1 and child2 are running in parallel calling their fooFunction */
child1.join();
child2.join();
/*Now i'm expecting that main thread will wait for child1and also for child2 (that are running in parallel).*/
... main thread starts again after both child1 and child2 finished (reached the await of the barrier)
... (break point set here, never reached)
...
Thread builder custom class
public class ThreadBuilderTask implements Runnable{
private CyclicBarrier barrier;
private int index;
...setters and getters..
#Override
public void run() {
fooFunction(this.getIndex());
try {
this.getBarrier().await();
} catch (InterruptedException | BrokenBarrierException e) {
return;
}
}
public ThreadBuilderTask(CyclicBarrier barrier,int index){
this.barrier = barrier;
this.index = index;
}
public fooFunction(int index){
//Something taking some seconds to execute
}
It's not clear what is happening here but it is definetely not working. As soon as i call join everything stops and the main thread never restart. (I put a breakpoint after the joins to see when the main thread restarts).
Maybe there is a bit of confusion with these concepts and also i'm not sure if i need to use both the barrier and the joins or simply one of those techniques.
Thanks
Davide
As mentioned in the comments I'd also suggest to use CompletableFuture. A very basic example of your described requirements could look like this:
final Runnable runnable1 = ...;
final Runnable runnable2 = ...;
CompletableFuture<Void> future1 = CompletableFuture.runAsync(runnable1);
CompletableFuture<Void> future2 = CompletableFuture.runAsync(runnable2);
CompletableFuture.allOf(future1, future2).get(); // waits for both runnables to finish
You might want to add more/some exception handling to this example. But it should give an idea how this might work.
You may consider to use Java CompletableFuture to achieve the objective.
Using its functions like supplyAsync or runAsync you may start child threads and join their respective result in the end. Or you can simply let the main thread wait until the subsequent threads completes.
Recently I managed to implement a sample scatter-gather function using the same class.
Check Java Doc for more offerings and to find best available function: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
Related
Java Concurrency In Practice, 12.1.2. Testing Blocking Operations:
void testTakeBlocksWhenEmpty() {
final BoundedBuffer<Integer> bb = new BoundedBuffer<Integer>(10);
Thread taker = new Thread() {
public void run() {
try {
int unused = bb.take();
fail(); // if we get here, it’s an error
} catch (InterruptedException success) { }
}
};
try {
taker.start();
Thread.sleep(LOCKUP_DETECT_TIMEOUT);
taker.interrupt();
taker.join(LOCKUP_DETECT_TIMEOUT);
assertFalse(taker.isAlive());
} catch (Exception unexpected) {
fail();
}
}
This is one of the few cases in which it is appropriate to subclass
Thread explicitly instead of using a Runnable in a pool: in order to
test proper termination with join. The same approach can be used to
test that the taker thread unblocks after an element is placed in the
queue by the main thread.
But I don't see how extending Thread helps with testing that. For me it seems that the same test could be done with passing Runnable to Thread. Can somebody explain that?
This is one of the few cases in which it is appropriate to subclass
Thread explicitly instead of using a Runnable in a pool: in order to
test proper termination with join.
In other words that approach lets you a chance to interrupt the test thread and join it to make sure it has been terminated properly. You can't handle threads in that way if you use, for example - ThreadPoolExecutor class.
Also, it is OK to create a new thread, initiating it with Runnable, like Thread taker = new Thread(() -> {...});. Remember that the book was written about 8 years ago, and creating Runnable instead of subclass of Thread would make that example a bit longer.
I have to make operations on a cache using many threads and thus have created 3 classes that extends from Thread (I realize now they can be Runnables also, or should be). Careful to note, these I'm running more than 1 instance of one of these threads but not at the same time. As in:
public class Operation1 extends Thread
public class Operation2 extends Thread
public class Operation3 extends Thread
Thread[] operation1Threads = new Thread[5];
So after I finish with this one, I create new threads for the second operation (at random).
The following is the way my run method is created.
I make use of cyclic barriers to wait for the threads to work at the same time.
public volatile boolean running = true;
public void run() {
while (running) {
cyclicbarrier1.await();
//some operation here
cyclicbarrier2.await();
}
}
The main thread is focusing on how long to run these for and at the end of that time, I try to stop the threads before working on the second operation. But it seems that my threads don't actually stop.
EDIT: I should note that I've tried interrupting the thread directly. And tried to reset the barrier both of which seemed to be bad practices from answers found on other threads.
for (int i=0; i < numthreads; i++) {
ops[i].interrupt();
}
I use an ExecutorService to manage these operations sequentially.
ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Operation1Runnable());
es.submit(new Operation2Runnable());
But the executorservice doesn't go to the next one.
I need to implement a test that uses threads in Java that waits for a condition, then does something to make the condition be false and during that check the condition is false. The exact scenario is below. I am new to threads in general, and threads in Java in particular (never used threads in any coding language). The scenario is like this:
wait for a file in linux to have the value 1 (using cat on the file)
once the value 1 is found, run ping on the linux machine, during the ping I need to verify the value in the same file is 0 during the entire ping session
after ping ends I need to verify the value in the file is 1 again
Could you direct me to a simple example on how to do this in Java using threads?
Thanks..
The general approach is to start a thread and use some synchronisation mechanizm to identify when your thread compleate the job.
One of the methods can be using of ExecutorService and awaitTermination, second approach may be using of CountDownLatch:
CountDownLatch latch = new CountDownLatch(2);
Thread myThead1 = new MyThread(latch);
Thread myThead2 = new MyThread(latch);
myThread1.start();
myThread2.start();
// This will block execution until myThead1 and myThead2 will call countDown:
latch.await();
The thread implementation should call countDown method after job is complited:
public class MyThread extends Thread {
private final CountDownLatch latch;
public MyThread(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
// do your job here
latch.countDown();
}
}
Please check java-doc for java.util.concurrent.locks.Condition. There is a good example that you can use as a base for your code.
I want to run several threads and join them at the end of my main method, so I can know when they have finished and process some info.
I don't want to put my threads in an array and do a join() one by one as join is a blocking method and I stay would waiting in the main thread for some threads still running, while other threads may have already finished, without having a possibility of knowing.
I have thought on the possibility of implementing an observer pattern for my threads: An interface with a update() method, an abstract class extending from thread (or implementing runnable) with set and get methods for the listeners and a class starting all my threads and waiting them to finish.
If my understanding is right, an observer would not block in a specific join() for a thread. Instead it will wait somehow until an update() method is called by a thread to perform an action. In this case, the update() should be called right after the thread finishes.
I'm clueless on how to implement this. I've tried with similar models, but I don't know how to use the observer/listener to wake/block my main thread. I've used this old post as a template: How to know if other threads have finished? but I can't find a way to wake my main method once a thread calls the update() method. There will be only one observer object instantiated for all threads.
Could you think of a way to use an observer pattern to wait for all threads to finish without blocking main with one by one join() calls? Any other suggestion to solve this problem would be greatly appreciated. Thanks in advance.
Java already has an API to do that: a CompletionService.
A service that decouples the production of new asynchronous tasks from the consumption of the results of completed tasks. Producers submit tasks for execution. Consumers take completed tasks and process their results in the order they complete.
I think you don't need an observer pattern. Thread waiting for any results will have to block, otherwise it will finish or loop in infinity. You can use some kind of BlockingQueue - producers will add result of computation to the blocking queue (then finish) and main thread will just receive these results blocking when there's not any result yet..
Good news for you, it's already implemented :) Great mechanism of CompletionService and Executors framework. Try this:
private static final int NTHREADS = 5;
private static final int NTASKS = 100;
private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);
public static void main(String[] args) throws InterruptedException {
final CompletionService<Long> ecs = new ExecutorCompletionService<Long>(exec);
for (final int i = 0; i < NTASKS ; ++i) {
Callable<Long> task = new Callable<Long>() {
#Override
public Long call() throws Exception {
return i;
}
};
ecs.submit(task);
}
for (int i = 0; i < NTASKS; ++i) {
try {
long l = ecs.take().get();
System.out.print(l);
} catch (ExecutionException e) {
e.getCause().printStackTrace();
}
}
exec.shutdownNow();
exec.awaitTermination(50, TimeUnit.MILLISECONDS);
}
Sounds to me like you are looking for something like the Counting Completion Service recently discussed by Dr. Heinz M. Kabutz.
I am practising threads, I used yield(), iam expecting output as below: (BUT not getting as expected)
One1
Two1
One2
Two2
One3
Two3
.
.
.
.
Whats wrong in my below code?
public class Main2 {
public static void main(String[] args) {
MyThread myThread1 = new MyThread("One");
MyThread myThread2 = new MyThread("Two");
/*Thread t1 = new Thread(myThread1);
Thread t2 = new Thread(myThread2);
t1.start();
t2.start();*/
myThread1.start();
myThread2.start();
}
}
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run(){
for(int i=1;i<=20;i++) {
System.out.println(name+i);
yield();
}
}
}
and also I would like to know does commented statements correct to use or not? I mean below:
Thread t1 = new Thread(myThread1);
Thread t2 = new Thread(myThread2);
t1.start();
t2.start();
Waiting for your replies..
The yield() method clearly states in its javadoc that it is
A hint to the scheduler that the current thread is willing to yield
its current use of a processor. The scheduler is free to ignore this
hint.
As such, you can't always expect execution to pass to another thread. There is no guarantee.
Also, in your question does commented statements correct to use or not, no, it won't change anything. The Thread constructor accepts a Runnable argument on which it will eventually execute the run() method. The Thread class implements Runnable and is therefore a valid argument, but it has the same effect as if you had started the Thread itself.
If you extend thread, you do it the way you have. If you implements Runnable, you do it the commented way. Either way is fine.
Note that yield is really just a recommendation, so the order of your output is not determined. You need to use locks or another technique if you want it to always be that certain way.
Thread#yield states that
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
So you won't get expected output here.
If you want expected output use wait() and notify() methods with proper synchronization.
I would like to know does commented statements correct to use or not?
Yes this is 100% valid java syntax.