Simple example to understand the concept of join() in Thread - java

I am studying the Threads in java.
I just want a simple example which explains the use of join() in Thread. I have seen this link..
Understanding join() method example
But still not able to understand the concept.
Can anybody explain me the concept of using the join() in Thread.
Any explanation retlated to this will be very helpful to me.
Thanks.

The simplest explanation I can come up is that join makes the caller thread wait for the completion of specified thread.
Say if you have a "main thread" and "thread A", if from the main thread you call A.join(), the main thread will wait until thread A finishes.
The java se manual page about concurrency should help you here: http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html

Thread.join() causes the current thread to wait for the thread you call join() on to die before it resumes execution.

Thread.join() blocks (does not return) until the thread you joined on has finished.
This is not the only way to wait for a thread to finish, but it is the most CPU-usage friendly way. Imagine if you had a loop like this (pseudocode):
while(!thread.isAlive())
{
Sleep(1);
}
This supposedly does the same thing... but, 1000 times per second, it will wake up, check the variable and go back to sleep. This means 1000 context switches (which are expensive) and the program will be slower as a result. This is called 'spinlocking' or 'busywaiting' and is frowned upon in programming as it consumes CPU for no reason.

I did some experiment and here is the result: 1. first started thread t3. 2. started t1 then 3. created t2 and t2 joinned the running thread t1.
By definition, t2 should wait for t1 to die and then it should start.
Observation: I called wait on t1, so t1 is paused but not died but I see then t2 is started why ?
public class TestThreadJoin {
public static void main(String[] args) {
final Thread t3 = new Thread(new Runnable() {
public void run() {
System.out.println("R3");
}
});
t3.start();
final Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("R1 before");
try {
perform();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("R1 after");
}
private void perform() throws InterruptedException {
synchronized(this){
wait(5000);
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("R2");
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
}
}

Related

Join() Method query

I am learning how to use the join() in multithreading.I have a doubt in the following program.
When the main method first call the t1.join() does it put both the main thread as well as the t2 thread to wait or it is only the main thread that goes to wait?
public class App {
private int count = 0;
public void increment(){
count++;
}
public static void main(String[] args) {
App app=new App();
app.dowork();
}
public void dowork() {
Thread t1 = new Thread(new Runnable(){
public void run(){
for(int i=0;i<10000;i++){
increment();
}
}
});
Thread t2=new Thread(new Runnable(){
public void run(){
for(int i=0;i<10000;i++){
increment();
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("count is " + count);
}
}
You should read up a bit. Jenkov's multithreading walkthrough explains multithreading in detail without overloading you with information. To answer; you cause the main thread to wait until completion of the first thread and then wait for the completion of the second thread. But if you look closely, Consider the following:
You have 3 threads, the main thread, thread 1 and thread 2. The main thread starts the other two threads and then waits on thread 1. However both thread 1 and thread 2 are allowed to continue and only the main thread will be waiting until thread 1 is complete. If thread 2 would still be alive after completion of thread 1, the main thread will be waiting for thread 2.
Here only your main thread will be suspended until t1 thread finishes. After that also main thread will wait until t2 finishes.
When you t1.join() the main thread blocks and waits for thread t1 to finish. Thread t2 is unaffected. Once t1 completes the main thread will resume then execute t2.join() where it will wait for t2 to finish.
t1.join() causes the calling thread (presumably in this case main) to wait for t1. Similarly for t2.join()

Deadlocks using wait and notify

I am trying to understand how deadlocks are created. I've understood that by using two threads on two synchronized methods, a deadlock can be created.
Went through many examples from the net.
Can a deadlock be created with wait and notify?
Every time a thread is on wait, it will be notified. So how does this end up in a deadlock?
Illustration of an example will be helpful.
Deadlock is caused when two threads try to obtain the same, multiple locks in different order:
// T1
synchronized (A) {
synchronized (B) {
// ...
}
}
// T2
synchronized (B) {
synchronized (A) {
// ...
}
}
The only way to prevent deadlocks is to make sure that all threads obtain locks in the same order--either they all do A then B, or they all do B then A.
If you don't have multiple locks, then you don't have a deadlock. However, you can get thread starvation or other things that may look similar to deadlock.
Say thread 1 enters a synchronized block on method A and then waits. Thread 2 then attempts to enter the synchronized block on method A. Thread 1 is waiting for a notify, and thread 2 is waiting on the synchronized block. Everything is now waiting. Some other thread will have to notify the object on which thread 1 is waiting. This is just one scenario that can create a deadlock. There are all kinds of ways to do it.
A thread which is on wait will not be notified unless some code explicitly notifies it. Therefore the example you are looking for is absolutely trivial:
public static void main(String[] args) {
synchronized(String.class) {
String.class.wait();
}
}
and this hangs forever. Technically, though, it is not a deadlock, which requires two or more threads involved in a closed cycle where each thread waits for the next one to unblock it.
Something close to wait/notify deadlock:
public class Example
{
volatile boolean isNotified = false;
public synchronized void method1() {
try
{
isNotified = false;
while (!isNotified)
wait();
notifyAll();
System.out.println("Method 1");
} catch (InterruptedException e) {/*NOP*/}
}
public synchronized void method2() {
try {
isNotified = true;
while (isNotified)
wait();
notifyAll();
System.out.println("Method 2");
} catch (InterruptedException e) {/*NOP*/}
}
public static void main(String[] args)
{
Example example = new Example();
Thread thread1 = new Thread()
{
public void run()
{
example.method1();
}
};
Thread thread2 = new Thread()
{
public void run()
{
example.method2();
}
};
thread1.start();
thread2.start();
}
}

What does this thread join code mean?

In this code, what does the two joins and break mean? t1.join() causes t2 to stop until t1 terminates?
Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread t2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
try {
t1.join();
t2.join();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
What does this thread join code mean?
To quote from the Thread.join() method javadocs:
join() Waits for this thread to die.
There is a thread that is running your example code which is probably the main thread.
The main thread creates and starts the t1 and t2 threads. The two threads start running in parallel.
The main thread calls t1.join() to wait for the t1 thread to finish.
The t1 thread completes and the t1.join() method returns in the main thread. Note that t1 could already have finished before the join() call is made in which case the join() call will return immediately.
The main thread calls t2.join() to wait for the t2 thread to finish.
The t2 thread completes (or it might have completed before the t1 thread did) and the t2.join() method returns in the main thread.
It is important to understand that the t1 and t2 threads have been running in parallel but the main thread that started them needs to wait for them to finish before it can continue. That's a common pattern. Also, t1 and/or t2 could have finished before the main thread calls join() on them. If so then join() will not wait but will return immediately.
t1.join() means cause t2 to stop until t1 terminates?
No. The main thread that is calling t1.join() will stop running and wait for the t1 thread to finish. The t2 thread is running in parallel and is not affected by t1 or the t1.join() call at all.
In terms of the try/catch, the join() throws InterruptedException meaning that the main thread that is calling join() may itself be interrupted by another thread.
while (true) {
Having the joins in a while loop is a strange pattern. Typically you would do the first join and then the second join handling the InterruptedException appropriately in each case. No need to put them in a loop.
This is a favorite Java interview question.
Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
try {
t1.join(); // 1
t2.join(); // 2 These lines (1,2) are in in public static void main
break;
}
}
t1.join() means, t1 says something like "I want to finish first". Same is the case with t2. No matter who started t1 or t2 thread (in this case the main method), main will wait until t1 and t2 finish their task.
However, an important point to note down, t1 and t2 themselves can run in parallel irrespective of the join call sequence on t1 and t2. It is the main/daemon thread that has to wait.
join() means waiting for a thread to complete. This is a blocker method. Your main thread (the one that does the join()) will wait on the t1.join() line until t1 finishes its work, and then will do the same for t2.join().
A picture is worth a thousand words.
Main thread-->----->--->-->--block##########continue--->---->
\ | |
sub thread start()\ | join() |
\ | |
---sub thread----->--->--->--finish
Hope to useful, for more detail click here
When thread tA call tB.join() its causes not only waits for tB to die or tA be interrupted itself but create happens-before relation between last statement in tB and next statement after tB.join() in tA thread.
All actions in a thread happen-before any other thread successfully returns from a join() on that thread.
It means program
class App {
// shared, not synchronized variable = bad practice
static int sharedVar = 0;
public static void main(String[] args) throws Exception {
Thread threadB = new Thread(() -> {sharedVar = 1;});
threadB.start();
threadB.join();
while (true)
System.out.print(sharedVar);
}
}
Always print
>> 1111111111111111111111111 ...
But program
class App {
// shared, not synchronized variable = bad practice
static int sharedVar = 0;
public static void main(String[] args) throws Exception {
Thread threadB = new Thread(() -> {sharedVar = 1;});
threadB.start();
// threadB.join(); COMMENT JOIN
while (true)
System.out.print(sharedVar);
}
}
Can print not only
>> 0000000000 ... 000000111111111111111111111111 ...
But
>> 00000000000000000000000000000000000000000000 ...
Always only '0'.
Because Java Memory Model don't require 'transfering' new value of 'sharedVar' from threadB to main thread without heppens-before relation (thread start, thread join, usage of 'synchonized' keyword, usage of AtomicXXX variables, etc).
Simply put:
t1.join() returns after t1 is completed. It doesn't do anything to thread t1, except wait for it to finish.
Naturally, code following
t1.join() will be executed only after
t1.join() returns.
From oracle documentation page on Joins
The join method allows one thread to wait for the completion of another.
If t1 is a Thread object whose thread is currently executing,
t1.join() : causes the current thread to pause execution until t1's thread terminates.
If t2 is a Thread object whose thread is currently executing,
t2.join(); causes the current thread to pause execution until t2's thread terminates.
join API is low level API, which has been introduced in earlier versions of java. Lot of things have been changed over a period of time (especially with jdk 1.5 release) on concurrency front.
You can achieve the same with java.util.concurrent API. Some of the examples are
Using invokeAll on ExecutorService
Using CountDownLatch
Using ForkJoinPool or newWorkStealingPool of Executors(since java 8)
Refer to related SE questions:
wait until all threads finish their work in java
For me, Join() behavior was always confusing because I was trying to remember who will wait for whom.
Don't try to remember it that way.
Underneath, it is pure wait() and notify() mechanism.
We all know that, when we call wait() on any object(t1), calling object(main) is sent to waiting room(Blocked state).
Here, main thread is calling join() which is wait() under the covers. So main thread will wait until it is notified.
Notification is given by t1 when it finishes it's run(thread completion).
After receiving the notification, main comes out of waiting room and proceeds it's execution.
Hope it helps!
package join;
public class ThreadJoinApp {
Thread th = new Thread("Thread 1") {
public void run() {
System.out.println("Current thread execution - " + Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
}
}
};
Thread th2 = new Thread("Thread 2") {
public void run() {
System.out.println("Current thread execution - " + Thread.currentThread().getName());
//Thread 2 waits until the thread 1 successfully completes.
try {
th.join();
} catch( InterruptedException ex) {
System.out.println("Exception has been caught");
}
for (int i = 0; i < 10; i++) {
System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
}
}
};
public static void main(String[] args) {
ThreadJoinApp threadJoinApp = new ThreadJoinApp();
threadJoinApp.th.start();
threadJoinApp.th2.start();
}
//Happy coding -- Parthasarathy S
}
The join() method is used to hold the execution of currently running thread until the specified thread is dead(finished execution).
Why we use join() method?
In normal circumstances we generally have more than one thread, thread scheduler schedules the threads, which does not guarantee the order of execution of threads.
Let's take a look at an example, create new project and copy the following code:
this is activity_main.xml code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_without_join"
app:layout_constraintTop_toTopOf="parent"
android:text="Start Threads Without Join"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_with_join"
app:layout_constraintTop_toBottomOf="#id/btn_without_join"
android:text="Start Threads With Join"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tv"
app:layout_constraintTop_toBottomOf="#id/btn_with_join"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is code for MainActivity.java:
public class MainActivity extends AppCompatActivity {
TextView tv;
volatile String threadName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
Button btn_without_join = findViewById(R.id.btn_without_join);
btn_without_join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
withoutJoin();
}
});
Button btn_with_join = findViewById(R.id.btn_with_join);
btn_with_join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
withJoin();
}
});
}
private void withoutJoin()
{
tv.setText("");
Thread th1 = new Thread(new MyClass2(), "th1");
Thread th2 = new Thread(new MyClass2(), "th2");
Thread th3 = new Thread(new MyClass2(), "th3");
th1.start();
th2.start();
th3.start();
}
private void withJoin()
{
tv.setText("");
Thread th1 = new Thread(new MyClass2(), "th1");
Thread th2 = new Thread(new MyClass2(), "th2");
Thread th3 = new Thread(new MyClass2(), "th3");
th1.start();
try {
th1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
th2.start();
try {
th2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
th3.start();
}
class MyClass2 implements Runnable{
#Override
public void run() {
Thread t = Thread.currentThread();
runOnUiThread(new Runnable() {
public void run() {
tv.setText(tv.getText().toString()+"\n"+"Thread started: "+t.getName());
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
tv.setText(tv.getText().toString()+"\n"+"Thread ended: "+t.getName());
}
});
}
}
}
This will be the result if you press first button (Start Threads Without Join):
And this will be the result if you press second button (Start Threads With Join):
let's say our main thread starts the threads t1 and t2. Now, when t1.join() is called, the main thread suspends itself till thread t1 dies and then resumes itself.
Similarly, when t2.join() executes, the main thread suspends itself again till the thread t2 dies and then resumes.
So, this is how it works.
Also, the while loop was not really needed here.

Make waiting thread skip the rest of the wait/continue

I have a scenario where I have one thread that loops between waiting and executing a task. However, I would like to interrupt the wait for the thread (skip the rest of the wait if you will) and continue on to doing the task.
Anyone have any ideas how this could be done?
I think what you need is implement wait()/notify() ! check it out this tutorial: http://www.java-samples.com/showtutorial.php?tutorialid=306
There are a lot of them out there! if you need a more specific case, post a bit of your code!
cheers
You could use wait() and notify(). If your thread is waiting, you'll need to resume it by calling notify() from a different thread.
This is what Thread.interrupt is for:
import java.util.Date;
public class Test {
public static void main(String [] args) {
Thread t1 = new Thread(){
public void run(){
System.out.println(new Date());
try {
Thread.sleep(10000); // sleep for 10 seconds.
} catch (InterruptedException e) {
System.out.println("Sleep interrupted");
}
System.out.println(new Date());
}
};
t1.start();
try {
Thread.sleep(2000); // sleep for 2 seconds.
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt();
}
}
Thread t1 will only sleep for 2 seconds, since the main thread interrupts it. Keep in mind that this will interrupt many blocking operations such as IO.

Variable interference with threads

Thread t1= new Thread(new Runnable() {
public void run() {
//perform Database stuff
}
});
t1.start();
initCache();//perform other Database stuff (Can this code be executed while thread 1 is running?)
How can I make sure the initCache method is forced to wait after t1 finishes?
Don't run it in a different thread to start with?
You could call t1.join() but really, if you want to run task X and then task Y, just run them in the same thread...
If you want initCache() to only run after t1 has finished running, then why do you start t1 in the first place?
Simply execute the code in run() and then initCache().
If there's some other action happening between t1.start() and initCache(), then you could use t1.join() to wait for t1 to finish before calling initCache().
Using join()? Seriously? Did the 90's called because they want their low-level synchronization facilities back?
What about something a bit more high-level? Like a CountDownLatch?
final CountDownLatch cdl = new CountDownLatch(1);
Thread t1= new Thread(new Runnable() {
public void run() {
//perform Database stuff
cdl.countDown();
}
});
t1.start();
cdl.await();
initCache();
Can also be configured with a timeout etc.
while (t1.isAlive()) {
try {
Thread.currentThread().sleep();
}
catch (InterruptedException e) {
//check again
}
}
initCache();
That should do it. Although actually the t1.join() method is a hell of a lot simpler.

Categories

Resources