I have two classes that extend Thread and a wait/notify
class A extends Thread {
int r = 20;
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
notify();
}
}
}
class B extends Thread {
A a;
public B(A a) {
this.a = a;
}
public void run() {
synchronized (a) {
System.out.println("Starting...");
try {
a.wait();
} catch (InterruptedException e) {
}
System.out.println("Result is: " + a.r);
}
}
}
Class A notifies Class B upon end of execution
A a = new A();
new B(a).start();
new B(a).start();
new B(a).start();
And the following code
a.start();
Notifies all threads
new Thread(a).start();
Notifies one thread
Why does a.start() notify all threads?
It's not
a.start();
that notifies all threads. It's the fact that the thread referenced by a terminates that notifies all threads waiting on its monitor.
This is explained in the javadoc
As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
On the other hand, in
new Thread(a).start();
you're using a as a Runnable, not as a Thread. The actual thread that will invoke this.notifyAll is the one created by the instance creation expression new Thread(a), which no other thread has called Object#wait() on.
Related
I am trying to implement Linux pipe operator | using java. The basic idea is assigning connected PipedInputStream and PipeOutputStream to the two commands and they can perform their actions simultaneously.
The implementation is as follows:
PipedOutputStream pOutputStream = new PipedOutputStream();
PipedInputStream pInputStream = new PipedInputStream();
pOutputStream.connect(pInputStream);
Thread thread1, thread2;
thread1 = new Thread(){
public void run() {
try {
new Call(pipe.cmd1).eval(CommandHandler.this, inputStream, pOutputStream);
pOutputStream.close();
} catch (Exception e) {
thread2.interrupt(); // cannot do this as it may not have been initialized
}
}
};
thread2 = new Thread() {
public void run() {
try{
new Pipe(pipe.cmd2).eval(CommandHandler.this, pInputStream, outputStream);
// pInputStream.close();
} catch (Exception e) {
// kill the first thread when the second one raises an exception
thread1.interrupt();
throw e;
}
}
};
thread1.start();
thread2.start();
// waiting for the two threads to die before carry on
thread2.join();
thread1.join();
I would like to interrupt the second thread when the first one raises an exception, just like what I did in thread2 catch. The problem is thread2 is assigned latter so I cannot access it within thread1. I tried to inialize thread1&2 with null values but then they have to be final since they are in an enclosing scope.
Forgive me if it is a stupid question, I just get started to explore multi-threading in java.
** UPDATE **
Thanks to Phil's suggestions. I changed the two anonymous inner classes to two inner classes that extends Thread.
class Thread1 extends Thread{
public Thread counterThread;
public void run() {
try {
new Call(pipe.cmd1).eval(CommandHandler.this, inputStream, pOutputStream);
pOutputStream.close();
} catch (Exception e) {
// kill thread 2
if (counterThread != null) counterThread.interrupt();
}
}
public void setThread(Thread thread) {
counterThread = thread;
}
};
class Thread2 extends Thread {
public Thread counterThread;
public void run() {
try{
new Pipe(pipe.cmd2).eval(CommandHandler.this, pInputStream, outputStream);
// pInputStream.close();
} catch (Exception e) {
// kill the first thread when the second one raises an exception
if (counterThread != null) counterThread.interrupt();
throw e;
}
}
public void setThread(Thread thread) {
counterThread = thread;
}
};
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.setThread(thread2);
thread2.setThread(thread1);
Given the code you've started with, two possibilities come to mind. There may be better ideas, but here they are:
(1) Add an additional public method in your anonymous inner class definition that allows you to store a reference to an external thread to be messaged/interrupted. After you create both threads, store a reference of each in the other.
(2) Store a reference to a class (possible the same class that creates and launches the threads) that will hold references to each thread. Have the catch method call a method in that launching class that will message (via loose coupling pattern) or interrupt the counterpart.
I am writing a program to test how a thread can keep waiting if another thread has acquired lock on same object but after looking at output I am not sure how locking works in java. Here is what i have written:
public class Locking {
synchronized void methodA() {
System.out.println("inside A , " + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
new Locking().execute();
}
private void execute() throws InterruptedException {
Thread t1 = new Thread(new MyThread());
t1.setName("t1");
Thread t2 = new Thread(new MyThread());
t2.setName("t2");
t1.start();
Thread.sleep(5000);
t2.start();
}
class MyThread implements Runnable {
#Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
methodA();
}
}
}
}
I expected thread t2 to be waiting forever and program will print only
inside A , t1
but when i run the program , I get following output:
inside A , t1
inside A , t2
Can anyone explain what is going on here?
I am writing a program to test how a thread can keep waiting if
another thread has acquired lock on same object
The single lock is here :
synchronized void methodA() {
System.out.println("inside A , " + Thread.currentThread().getName());
}
It takes the locks on the current instance but no statement in your code locks in a way where a thread could wait forever the lock.
Look at my comments :
#Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// the lock is set here
methodA();
// and that is released here
}
}
Make the synchronized method never releases the lock and only one of the thread will be able to enter in :
synchronized void methodA() {
while (true) {
System.out.println("inside A , " + Thread.currentThread()
.getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// handle it
}
}
}
prints :
inside A , t1
inside A , t1
inside A , t1
...
Her are some other examples to play with threads.
Replace sleep() by wait() and the current thread will release the lock :
synchronized void methodA() {
while (true) {
System.out.println("inside A , " + Thread.currentThread()
.getName());
try {
wait();
} catch (InterruptedException e) {
// handle it
}
}
}
prints :
inside A , t1
inside A , t2
Use notify() (to notify a waiting thread) and wait() (to make the current thread wait and release the lock if it has) to make threads collaborating between them :
synchronized void methodA() {
while (true) {
notify();
System.out.println("inside A , " + Thread.currentThread()
.getName());
try {
wait();
} catch (InterruptedException e) {
// handle it
}
}
}
prints :
inside A , t1
inside A , t2
inside A , t1
inside A , t2
...
That is intended situation.
Your t1 thread is waiting in another thread not main thread.
In your main thread(make threads and call start()), just waiting 5 seconds and start thread2
your synchronized method is synchronizing only when thread 1 calls that method not forever.
After thread1 calls synchorinized method and return, thread1 is stopping 5seconds.
In that time, thread2 can use that method.
The keyword synchronized infront of a method means, that the method cannot be called by two threads at the same time.
As soon as the method is called by a thread, other threads trying to call that same method are blocked until the first thread returns from that method. Afterwards the other threads calling the same method can automatically continue with the call (one at a time).
You implicit lock with synchronized is working for a short period - that is the println after that the lock is released. Both of your threads are racing to obtain the lock there.
Change your code to this and you will see the behavior you want
class MyThread implements Runnable {
#Override
public void run() {
methodA();
}
}
synchronized void methodA() {
while(true)
System.out.println("inside A , " + Thread.currentThread().getName());
}
I was trying to create A Java dead lock program . I know in real time we wont be creating any dead lock in thread. Unfortunately I have been asked in one of the interview to writing a "Deadlock program using two threads". So here it is
package Thread.DeadLock;
public class deadLock2 {
static ThreadSample1 t1 = new ThreadSample1();
static ThreadSample2 t2 = new ThreadSample2();
public static void main(String args[]) {
t1.start();
t2.start();
}
public static class ThreadSample1 extends Thread {
public void run() {
System.out.println("In first run method");
try {
System.out.println("Holding lock in first one");
synchronized (t1) {
System.out.println("t1 going to wait for t2");
t1.wait();
System.out.println("t1 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class ThreadSample2 extends Thread {
public void run() {
System.out.println("In second run method");
try {
System.out.println("Holding lock for second one");
synchronized (t2) {
System.out.println("t2 going to wait for t1");
t2.wait();
System.out.println("t2 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I can see the program is getting stuck. I am assuming that it in deadlock situation. t1.start() waits for t2 to finish its task and t2.start() waits for t1 to finish its task. Now while I try to remove the deadlock by notifying the waiting thread using using t1.notify() I get IllegalMonitorStateException.
Can somebody tell in this situation how to remove the deadlock without causing any situation.
First, this is not deadlock. As you correctly described, deadlock is usually situation when there is circular dependency between two or more threads waiting for resources that is held by other thread.
Here, each thread independently waits for notification on itself which is actually not delivered by anybody else in the system. Even if there is no deadlock.
Secondly, IllegalMonitorStateException means that you try to notify/wait on monitor which is not held by the thread. In other words, there is no synchronized prior to notify/wait.
Third, to achieve real deadlock you can do something like this:
synchronized(t1) {
synchronized(t2) {
t2.wait();
}
t1.notify();
}
and vice versa for the other thread.
You can not call notify()/notifyAll() unless the current thread owns that object's monitor. To do that, you must synchronize on it, as you did with wait()
The Javadocs for wait() mention this:
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws:
IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.
And from notify():
A thread becomes the owner of the object's monitor in one of three
ways:
By executing a synchronized instance method of that object.
By executing the body of a synchronized statement that synchronizes on the object.
For objects of type Class, by executing a synchronized static method of that class.
See this answer:
Java Wait and Notify: IllegalMonitorStateException
package pck.pramod.geekforgeeks;
public class ThreadDeadlock {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
System.out.println(Lock1.toString() + " " + Lock2.toString());
ThreadDemo1 T1 = new ThreadDemo1(Lock1, Lock2, "T1");
ThreadDemo1 T2 = new ThreadDemo1(Lock2, Lock1, "T2");
T1.start();
T2.start();
}
}
class ThreadDemo1 extends Thread {
Object lock1;
Object lock2;
String name;
public ThreadDemo1(Object lock1, Object lock2, String name) {
this.lock1 = lock1;
this.lock2 = lock2;
this.name = name;
}
public void run() {
synchronized (lock1) {
System.out.println(name + " Holding lock ..." + lock1.toString());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println(name + " Waiting for lock ..." + lock2.toString());
synchronized (lock2) {
System.out.println(name + " Holding lock ..." + lock1.toString() + " " + lock2.toString());
}
}
}
}
Iam new to syncronization and multithreading please answer why this code is not getting a lock on object b.
public class Tetsclass {
public static void main(String[] args) {
B b = new B();
A a = new A(b);
A2 a2 = new A2(b);
Thread t1= new Thread(a);
Thread t2= new Thread(a2);
t1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
}
}
class B {
public synchronized void waitfor() {
synchronized (B.class) {
System.out.println("Lock aquired on "+System.currentTimeMillis());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Lock released");
}
}
public void readObject() {
System.out.println("readobject by thread==="+Thread.currentThread().getName()+" on "+System.currentTimeMillis());
}
}
class A2 implements Runnable {
B b=null;
public A2(B b) {
this.b = b;
}
#Override
public void run() {
b.readObject();
}
}
class A implements Runnable {
B b=null;
public A(B b) {
this.b = b;
}
#Override
public void run() {
b.waitfor();
}
}
I expected the output :
Lock aquired on 1380016080337
Lock released
readobject by thread===Thread-1 on 1380016082337
but the output is :
Lock aquired on 1380016080337
readobject by thread===Thread-1 on 1380016082337
Lock released
The readObject method, including its invocation from A2#run, involves no lock acquisition. Therefore the lock your other thread is holding is inconsequential to the progress of the execution of readObject.
Apparently you have a misunderstanding of the semantics of locks. You believe that when you lock B.class, you have locked "the whole class". The state of matters is quite different: B.class is just another object, and all objects have their associated monitor, which can be acquired by a thread. Mutual exclusion happens only between threads which contend to acquire one and the same lock. There is no semantic relationship between an object as a lock and any of its methods, and the same stands for class objects vz. instances of that class.
One way your misunderstanding may have arisen is via the objects used implicitly on synchronized methods: a synchronized instance method acquires its this as a lock, while a synchronized static method acquires a lock on its associated class object.
Its behaving as expected.
Here is what happens on the time line
a - calls wait (which sleeps 5 secs before releasing lock)
a2 - calls read which prints read message.
t t+dt t+dt+5
---------|-----------|--------------------------------|--------------------------|----------
[a starts] [print(lock acquired)] [sleeps(5)] [print(lock released)]
t+2
----------------------------|--------------|--------------------------|--------------
[a2 starts] [print(read message)]
There is no locking of any kind in your readObject()
Since the readObject() doesn't require to acquire a lock, it won't wait for the other thread to release the lock. This confusion might have come because of the Thread.sleep(2000) you've in your test class.
Try to change that to Thread.sleep(10000) and see the output. You'll get your desired result.
In the first case, the A2 thread will wait for 2 secs after A starts, and will execute without any further delay whereas your A is held up for 5 secs when it acquired the lock.
In the second case, the A2 thread will wait for 10 secs after A starts, and within those 10 secs, your A will start, sleep for 5 secs and release the lock, after which your A2 will be executed without any delays.
Class B object can be synchronized to get the output as expected. There is no synchronization is involve in current code execution. To synchronized this code and get the expected output, we can modify Class B as
class B {
public synchronized void waitfor() {
synchronized (B.class) {
System.out.println("Lock aquired on "+System.currentTimeMillis());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Lock released");
}
}
public void readObject() {
synchronized(B.class)
{
System.out.println("readobject by thread==="+Thread.currentThread().getName()+" on "+System.currentTimeMillis());
}
}
}
I'm trying to understand how threads work, and I wrote a simple example where I want to create and start a new thread, the thread, display the numbers from 1 to 1000 in the main thread, resume the secondary thread, and display the numbers from 1 to 1000 in the secondary thread. When I leave out the Thread.wait()/Thread.notify() it behaves as expected, both threads display a few numbers at a time. When I add those functions in, for some reason the main thread's numbers are printed second instead of first. What am I doing wrong?
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
#Override
public void run() {
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
t.start();
synchronized(t) {
try {
t.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}
You misunderstand how wait/notify works. wait does not block the thread on which it is called; it blocks the current thread until notify is called on the same object (so if you have threads A and B and, while in thread A, called B.wait(), this will stop thread A and not thread B - for as long as B.notify() is not called).
So, in your specific example, if you want main thread to execute first, you need to put wait() inside the secondary thread. Like this:
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
#Override
public void run() {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
t.start();
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}
However, even this code may not work like you want. In a scenario where the main thread gets to the notify() part before the secondary thread had a chance to get to the wait() part (unlikely in your case, but still possible - you can observe it if you put Thread.sleep at the beginning of the secondary thread), the secondary thread will never be waken up. Therefore, the safest method would be something similar to this:
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
#Override
public void run() {
synchronized (this) {
try {
notify();
wait();
} catch (InterruptedException e) {
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
synchronized (t) {
t.start();
try {
t.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}
In this example the output is completely deterministic. Here's what happens:
Main thread creates a new t object.
Main thread gets a lock on the t monitor.
Main thread starts the t thread.
(these can happen in any order)
Secondary thread starts, but since main thread still owns the t monitor, the secondary thread cannot proceed and must wait (because its first statement is synchronized (this), not because it happens to be the t object - all the locks, notifies and waits could as well be done on an object completely unrelated to any of the 2 threads with the same result.
Primary thread continues, gets to the t.wait() part and suspends its execution, releasing the t monitor that it synchronized on.
Secondary thread gains ownership of t monitor.
Secondary thread calls t.notify(), waking the main thread. The main thread cannot continue just yet though, since the secondary thread still holds ownership of the t monitor.
Secondary thread calls t.wait(), suspends its execution and releases the t monitor.
Primary thread can finally continue, since the t monitor is now available.
Primary thread gains ownership of the t monitor but releases it right away.
Primary thread does its number counting thing.
Primary thread again gains ownership of the t monitor.
Primary thread calls t.notify(), waking the secondary thread. The secondary thread cannot continue just yet, because the primary thread still holds the t monitor.
Primary thread releases the t monitor and terminates.
Secondary thread gains ownership of the t monitor, but releases it right away.
Secondary thread does its number counting thing and then terminates.
The entire application terminates.
As you can see, even in such a deceptively simple scenario there is a lot going on.
You are lucky that your program terminates at all.
When you call t.wait() your main threads stops and waits indefinitely on a notification.
It never gets it, but I believe is awaken by spurious wakeup when the secondary thread finishes. (Read here on what a spurious wakeup is).
ExampleThread doesn't wait() or notify(), and isn't synchronized on anything. So it will run whenever it can without any coordination with other threads.
The main thread is waiting for a notification which never comes (this notification should be sent by another thread). My guess is that when the ExampleThread dies, the main thread is woken "spuriously," and completes.
The thread that should wait for another to complete must perform the call to wait() inside a loop that checks for a condition:
class ExampleThread extends Thread {
private boolean ready = false;
synchronized void ready() {
ready = true;
notifyAll();
}
#Override
public void run() {
/* Wait to for readiness to be signaled. */
synchronized (this) {
while (!ready)
try {
wait();
} catch(InterruptedException ex) {
ex.printStackTrace();
return; /* Interruption means abort. */
}
}
/* Now do your work. */
...
Then in your main thread:
ExampleThread t = new ExampleThread();
t.start();
/* Do your work. */
...
/* Then signal the other thread. */
t.ready();