CyclicBarrier re-use Example - java

Does CyclicBarrier best suitable, in this case.
I want to run n threads parallel in Stages (wait at Stages until all threads completes that Stage).
public class CyclicBarr {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
private int count =1;
#Override
public void run() {
System.out.println("Completed..!! "+(count++));
}
});
for (int i = 1; i <= 3; i++) {
Thread t = new Thread(new CuclicBarThread(barrier));
t.start();
}
}
}
And Thread is
public class CuclicBarThread implements Runnable {
CyclicBarrier barrier;
public CuclicBarThread(CyclicBarrier barrier) {
this.barrier = barrier;
}
#Override
public void run() {
try {
for (int i = 1; i < 5; i++) {
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 1 After Stage 1 Completed");
barrier.await();
for (int i = 1; i < 5; i++) {
Thread.sleep(1000);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 2 After Stage 2 Completed");
barrier.await();
for (int i = 1; i < 5; i++) {
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 3 After Stage 3 Completed");
barrier.await();
System.out.println(Thread.currentThread().getName()+" :: $$$$$$$$ Completed $$$$$$$$");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Yes it is reusable. That is why it is called "Cyclic". Here is the quote from its JavaDoc:
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
And your usage of the CyclicBarrier seems fine to me.

Related

why thread isnt stopping at count 3?

I am trying to do a little exercise on threads and I just started learning thread and other stuff.
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadDemo extends Thread {
#Override
public void run() {
int count = 0;
for (int i = 0; i <= 5; i++) {
count++;
System.out.println("counting" + count);
}
if (count == 3) {
try {
Thread t = new Thread();
t.wait(5000);
System.out.println("thread waiting");
} catch (InterruptedException ex) {
Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) {
ThreadDemo obj = new ThreadDemo();
obj.start();
}
}
Output of the given
counting1
counting2
counting3
counting4
counting5
counting6
When the test if (count == 3) is done the value of count is 6.
And your code test it only once.
You need to move the code that is out of the for loop inside it.
You need also to hold a lock on t before call wait. This is done with a synchronized block.
#Override
public void run() {
int count = 0;
for (int i = 0; i <= 5; i++) {
count++;
System.out.println("counting" + count);
// Moved block
if (count == 3) {
try {
Thread t = new Thread();
synchronized (t) {
t.wait(5000);
}
System.out.println("thread waiting");
} catch (InterruptedException ex) {
Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
// End of moved block
}
}
The output will be
counting1
counting2
counting3
thread waiting // Note: this will be printed after 5 seconds
counting4
counting5
counting6
A similar result, but not identical can be obtained using Thread.sleep, replacing this code
Thread t = new Thread();
synchronized (t) {
t.wait(5000);
}
With the following:
Thread.sleep(5000);
A difference between Thread.sleep and Object.wait is that is possible to awake a thread waiting acquiring his lock and calling notify (or notifyAll).
Instead is not possible to awake a thread sleeping with Thread.sleep.

how to pause a thread and resume it exactly where it was left off

I'm trying to come with a solution for a thread to pause and resume exactly where it was left off.
So here's a sample code emulating my problem: 2 threads are running in the background: taskThread & busyThread. When busyThread is in system is busy area, taskThread must alt/pause immediately and resume exactly where it was left off. Example, if taskThread was paused at task C (finished) it should resume at D.
I tried to use wait, notify on taskThread but without success.
public class Test
{
private Thread taskThread;
private Thread busyThread;
public static void main(String args[]) throws Exception
{
Test t = new Test();
t.runTaskThread();
t.runBusyThread();
}
public void runTaskThread()
{
taskThread = new Thread(new Runnable(){
#Override
public void run()
{
for (int x=0; x<100; x++)
{
try
{
System.out.println("I'm doing task A for process #"+x);
Thread.sleep(1000);
System.out.println("I'm doing task B for process #"+x);
Thread.sleep(200);
System.out.println("I'm doing task C for process #"+x);
Thread.sleep(300);
System.out.println("I'm doing task D for process #"+x);
Thread.sleep(800);
System.out.println("\n\n");
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}});
taskThread.start();
}
public void runBusyThread()
{
busyThread = new Thread(new Runnable(){
#Override
public void run()
{
while (true)
{
Random rand = new Random();
int randomNum = rand.nextInt(1000);
if (randomNum<400)
{
System.out.println("Wait...system is busy!!!");
try
{ //what should come here to to signal taskThread to paused
Thread.sleep(3000);
//what should come here to to signal taskThread to resume
} catch (InterruptedException e)
{
}
} else
{
try
{
Thread.sleep(300);
} catch (InterruptedException e)
{
}
}
}
}});
busyThread.start();
}
}
There are two very useful classes in concurrency package - CountDownLatch and CyclicBarrier. If you need this behaviour only once, you probably want the first one (as it cannot be reset).
Thread 1 will await until notified by thread 2. Once it was counted down to 0, thread 1 will never block again at await():
CountDownLatch cdl = new CountDownLatch(1);
// thread 1:
cdl.await();
// thread 2:
cdl.countDown();
Threads will block at await() until there are exactly two threads waiting:
CyclicBarrier barrier = new CyclicBarrier(2);
// both threads:
barrier.await();
EDIT:
Here is what I came up with when modifying your code, however it is unclear to me whether it is expected behaviour.
Note a volatile keyword on the CountDownLatch - it is very important here, otherwise taskThread may cache the initial object (new CountDownLatch(0)) and hence never block.
public class Test {
private Thread taskThread;
private Thread busyThread;
private volatile CountDownLatch cdl = new CountDownLatch(0);
public static void main(String args[]) throws Exception {
Test t = new Test();
t.runTaskThread();
t.runBusyThread();
}
public void runTaskThread() {
taskThread = new Thread(() -> {
for (int x = 0; x < 100; x++) {
waitIfSystemBusy();
System.out.println("I'm doing task A for process #" + x);
sleep(1000);
waitIfSystemBusy();
System.out.println("I'm doing task B for process #" + x);
sleep(200);
waitIfSystemBusy();
System.out.println("I'm doing task C for process #" + x);
sleep(300);
waitIfSystemBusy();
System.out.println("I'm doing task D for process #" + x);
sleep(800);
System.out.println("\n\n");
}
});
taskThread.start();
}
public void runBusyThread() {
busyThread = new Thread(() -> {
while (true) {
Random rand = new Random();
int randomNum = rand.nextInt(1000);
if (randomNum < 400) {
System.out.println("Wait...system is busy!!!");
cdl = new CountDownLatch(1); // signal taskThread to pause
sleep(3000);
cdl.countDown(); // signal taskThread to resume
} else {
sleep(300);
}
}
});
busyThread.start();
}
private void waitIfSystemBusy() {
try {
cdl.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
It would be done using the deprecated methods Thread.suspend/resume.
They are deprecated as they are deadlock prone, whereas concurrency mechanisms like locks behave in a designed explicit manner (but still deadlock prone).
I would suggest create a class that implements Runnable which simply keep track of the stages you are in
just as an example (please change accordingly)
class MyRunnable implements Runnable {
private int stage = 0; // if you want it gloabally, then use static
#Override
public void run() {
try{
switch(stage){
case 1:
System.out.println("1");
stage++;
case 2:
System.out.println("2");
Thread.sleep(2000);
stage++;
default:
stage = 0;
}
}catch (Exception e){
}
}
}
now to use such class you just need to create a new thread
for example:
public static void main(String[] args) throws Exception{
MyRunnable myRunnable=new MyRunnable();
new Thread(myRunnable).start(); //it prints 1
Thread.sleep(1000);
new Thread(myRunnable).start(); //prints 2 follow by 2 sec sleep
}
NOTE:
this example wasn't intended to answer the question exactly but rather show a logic how it can be done.
EDIT 1:
what should come here to to signal taskThread to paused
taskThread.interupt();
what should come here to to signal taskThread to resume
taskThread=new Thread(myRunnable);
taskThread.start();
Instead of sleep() I would prefer wait() and notifyAll().
have a Boolean systemBusy, implement get and set methods;
now in thread1
run(){
synchronize(something){
while(isSystemBusy()){
try{
wait();}
catch{}
}
}
}
and on the other thread
run(){
setSystemBusy(true);
//piece of code
//task finished
notifyAll();
setSystemBusy(false);
}
you can use this in multiple waiting threads just remember to set appropriate while condition false after notify all.

How do I test the completion of threads created under my testmethod in JUnit

I have a method createThreads which spawns few new threads. Each of the newly created thread does some work. If I invoke the method `createThreads' in junit, how can i ensure that all the newly spawned threads have also completed successfully.
I am currently calling as below
#Test
public void test() {
createThreads(); // Does not wait until the newly created threads also finish.
}
public void createThreads()
{
ExecutorService executorService = Executors
.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
executorService.execute(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I have completed execution " + Thread.currentThread().getName());
}
});
}
Note that I cannot modify createThreads
a bit odd but..
you can probably get all the runing threads
through Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
then filter it to identify the thread from the executor service.
then do a .join() on each of those threads.
as i said, a bit odd but it should fit your needs ...
try running this, you'll see that they are quite easy to identify :
public static void main(String[] args) {
int nb = 3;
ExecutorService executorService = Executors.newFixedThreadPool(nb);
for (int i = 0; i < nb; i++) {
executorService.execute(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I have completed execution " + Thread.currentThread().getName());
}
});
}
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread t : threadSet) {
System.out.println(t.getName());
}
}
sorry for a 2nd answer not possible to add such a long code in comment

Java signal handling and then return to main program

MI have a program that starts with for loop and it spins for 10 times, and one loop lasts one second. I need to handle a signal (CTRL+C) and while handling it, it should do it's own for loop, and after it stops, then I should return to the main loop. I've managed to do almost everything above, but the loops don't execute separately. They do it parallel. Hope you can help... thanks :)
BTW, my code is:
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class MySig {
public static void shhh(int s){ //s -> seconds :)
s = s*1000;
try{
Thread.sleep(s);
}catch(InterruptedException e){
System.out.println("Uh-oh :(");
}
}
public static void main(String[] args){
Signal.handle(new Signal("INT"), new SignalHandler () {
public void handle(Signal sig) {
for(int i=0; i<5; i++){
System.out.println("+");
shhh(1);
}
}
});
for(int i=0; i<10; i++) {
shhh(1);
System.out.println(i+"/10");
}
}
}
Right, according to the docs, SignalHandler is executed in a separate thread:
...when the VM receives a signal, the special C signal handler creates a
new thread (at priority Thread.MAX_PRIORITY) to run the registered
Java signal handler..
If you want to stop your main loop while the handler is executing, you can add a locking mechanism, something like this:
private static final ReentrantLock lock = new ReentrantLock(true);
private static AtomicInteger signalCount = new AtomicInteger(0);
public static void shhh(int s) { // s -> seconds :)
s = s * 1000;
try {
System.out.println(Thread.currentThread().getName() + " sleeping for "
+ s + "s...");
Thread.sleep(s);
} catch (InterruptedException e) {
System.out.println("Uh-oh :(");
}
}
public static void main(String[] args) throws Exception {
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
// increment the signal counter
signalCount.incrementAndGet();
// Acquire lock and do all work
lock.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println("+");
shhh(1);
}
} finally {
// decrement signal counter and unlock
signalCount.decrementAndGet();
lock.unlock();
}
}
});
int i = 0;
while (i < 10) {
try {
lock.lock();
// go back to wait mode if signals have arrived
if (signalCount.get() > 0)
continue;
System.out.println(i + "/10");
shhh(1);
i++;
} finally {
// release lock after each unit of work to allow handler to jump in
lock.unlock();
}
}
}
There might be a better locking strategy.

Multithreaded in java

I have a multithreaded program where I want the one of the thread to print the statement after all the thread finished.How can I do that? and How do I know that all the threads finished?
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 0; i < myList.size(); ++i) {
pool.execute (new ThreadProcessRunnable (args));
}
public class ThreadProcessRunnable implements Runnable {
public void run() {
System.out.println("last thread should execute this");
}
}
That sounds like an ideal use case for ExecutorService.invokeAll:
ExecutorService pool = Executors.newCachedThreadPool();
List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
for(int i = 0; i < myList.size(); ++i) {
tasks.add (Executors.callable(new ThreadProcessRunnable (args)));
}
List<Future<Object>> futures = pool.invokeAll(tasks);
System.out.println("All tasks finished");
public class ThreadProcessRunnable implements Runnable {
public void run() {
// do some stuff
}
}
invokeAll blocks until all the tasks in the supplied List are complete.
If you absolutely must have the println inside one of the threads' run methods, then the simplest approach I can think of would be to keep some sort of counter in an AtomicInteger
public class ThreadProcessRunnable implements Runnable {
private AtomicInteger taskCounter;
public ThreadProcessRunnable(AtomicInteger counter) {
this.taskCounter = counter;
}
public void run() {
// do stuff
if(taskCounter.decrementAndGet() == 0) {
System.out.println("I am the last thread and I am about to finish");
}
}
}
// Main class
ExecutorService pool = Executors.newCachedThreadPool();
AtomicInteger taskCounter = new AtomicInteger(myList.size());
for(int i = 0; i < myList.size(); ++i) {
pool.execute(new ThreadProcessRunnable(taskCounter));
}
The key thing that makes this work is that taskCounter.decrementAndGet is atomic - if the value of taskCounter is initially 2, for example, and two different threads call decrementAndGet at the same time then it is guaranteed that one thread will see the value 1 and the other thread will see the value 0, so exactly one thread will print the "about to finish" message. This is different from MadProgrammer's answer, which involves a race condition:
latch.countDown();
if(latch.getCount() == 0) { ... }
where it is possible to have thread 1 decrement the value (to 1), then thread 2 decrement it again (to 0), then both threads see the value 0 when they call getCount and both print the message.
This is a REALLY basic example/concept of using a CountDownLatch
public class TestCountDownLatch {
private static CountDownLatch latch;
public static void main(String[] args) {
latch = new CountDownLatch(10);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; ++i) {
pool.execute(new Worker(i));
}
}
public static class Worker implements Runnable {
private int number;
public Worker(int number) {
this.number = number;
}
#Override
public void run() {
try {
System.out.println(number + " is sleeping...");
Thread.sleep((long) (Math.round(Math.random() * 1000)));
} catch (InterruptedException ex) {
}
System.out.println(number + " is Completed...");
latch.countDown();
if (latch.getCount() == 0) {
System.out.println(number + " was last...");
}
}
}
}
Simple Single Thread Test Case
public class TestCountDownLatch {
private static CountDownLatch latch;
public static void main(String[] args) {
latch = new CountDownLatch(1);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 1; ++i) {
pool.execute(new Worker(i));
}
}
public static class Worker implements Runnable {
private int number;
public Worker(int number) {
this.number = number;
}
#Override
public void run() {
try {
System.out.println(number + " is sleeping...");
Thread.sleep((long) (Math.round(Math.random() * 1000)));
} catch (InterruptedException ex) {
}
System.out.println(number + " is Completed...");
latch.countDown();
if (latch.getCount() == 0) {
System.out.println(number + " was last...");
}
}
}
}
You can use a CyclicBarrier with a barrier action (documentation).
Creates a new CyclicBarrier that will trip when the given number of
parties (threads) are waiting upon it, and which will execute the
given barrier action when the barrier is tripped, performed by the
last thread entering the barrier.
You can place it in the main thread. Call pool.await() to block the main thread until all threads in the pool have finished, then do the extra work. The code would look like this:
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 0; i < myList.size(); ++i) {
pool.execute (new ThreadProcessRunnable (args));
}
pool.shutdown();
pool.awaitTermination();//blocks the main thread
System.out.println("last thread should execute this");

Categories

Resources