java concurrency - interrupt a DeadLook thread - java

I'm trying to learn the basics of java concurrency, I start with oracle java tutorial until http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html, I just add some line to the code example,but when I run the code, the main method never return.
I know that both of alphonseThread and gastonThread are deadlocked by each ether, but why can't interrupt them from the main Thread?
public class DeadLock {
static class Freind {
private final String name;
public Freind(String name_) {
this.name = name_;
}
public String getName() {
return this.name;
}
public synchronized void bow(Freind bower) throws InterruptedException {
System.out.format("%s : %s " + "has bowed to me!%n",
this.name, bower.getName());
Thread.sleep(2000);
bower.bowBack(this);
}
public synchronized void bowBack(Freind bower) {
System.out.format("%s : %s " + "has bowed back to me!%n",
this.name, bower.getName());
}
}
#SuppressWarnings("SleepWhileInLoop")
public static void main(String[] args) throws InterruptedException {
// wait for 4 seconds before send a interuption signal
int patient = 4000;
int waitingUnit = 1000;
long start;
final Freind alphonse = new Freind("Alphonse");
final Freind gaston = new Freind("Gaston");
// the first thread
Thread alphonseThread = new Thread(new Runnable() {
#Override
public void run() {
try {
alphonse.bow(gaston);
} catch (InterruptedException ex) {
System.out.println("Alphnso have been killed");
}
}
});
// the second thread
Thread gastonThread = new Thread(new Runnable() {
#Override
public void run() {
try {
gaston.bow(alphonse);
} catch (InterruptedException ex) {
System.out.println("Gaston have been killed ");
}
}
});
// start the tow threads
start = System.currentTimeMillis();
alphonseThread.start();
gastonThread.start();
while (alphonseThread.isAlive() || gastonThread.isAlive()) {
if (((System.currentTimeMillis() - start) < patient)
&& (alphonseThread.isAlive() || gastonThread.isAlive())) {
System.out.println(System.currentTimeMillis() - start);
System.out.println("still waiting !!");
Thread.sleep(waitingUnit);
} else {
if (alphonseThread.isAlive()) {
alphonseThread.interrupt();
alphonseThread.join();
}
if (gastonThread.isAlive()) {
gastonThread.interrupt();
gastonThread.join();
}
}
}
System.out.println("finnaly I kill all of them");
}
}

but why can't interrupt them from the main Thread?
You can interrupt from the main thread (or anywhere). Just call Thread.interrupt() on the thread you want to interrupt.
The problem is that interrupt won't unblock a thread that is trying to acquire a Java primitive lock / mutex. In fact, I don't think there is anything that will safely unblock threads that are deadlocked on primitive locks.
If you want your application to be able to recover from deadlocks involving object locks, then you should probably be using Lock objects, and the Lock.lockInterruptibly() method ... which will unblock when the thread is interrupted.

Related

Synchronisation of Bow/Bower example in java oracle tutorial with reentrant lock

The code given here on https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html gives synchronisation of bow and bower with lock objects , so that it can avoid deadlock.
here is the code
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class Safelock {
static class Friend {
private final String name;
private final Lock lock = new ReentrantLock();
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean impendingBow(Friend bower) {
Boolean myLock = false;
Boolean yourLock = false;
try {
myLock = lock.tryLock();
yourLock = bower.lock.tryLock();
} finally {
if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}
}
return myLock && yourLock;
}
public void bow(Friend bower) {
if (impendingBow(bower)) {
try {
System.out.format("%s: %s has"
+ " bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
} finally {
lock.unlock();
bower.lock.unlock();
}
} else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
}
public void bowBack(Friend bower) {
System.out.format("%s: %s has" +
" bowed back to me!%n",
this.name, bower.getName());
}
}
static class BowLoop implements Runnable {
private Friend bower;
private Friend bowee;
public BowLoop(Friend bower, Friend bowee) {
this.bower = bower;
this.bowee = bowee;
}
public void run() {
Random random = new Random();
for (;;) {
try {
Thread.sleep(random.nextInt(10));
} catch (InterruptedException e) {}
bowee.bow(bower);
}
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new BowLoop(alphonse, gaston)).start();
new Thread(new BowLoop(gaston, alphonse)).start();
}
}
My Question is - supposedly thread 1 - alphanso thread and thread 2 - gaston thread executes at same pace all the time. So they will call impendingBow() together. Both of them tries to acquire lock of itself and another object and if any of the lock is not available then they release the acquired lock if any.
Now if both threads are executing lines in same rate , So alphanso thread will be able to get lock of itself and so will gaston but both will fail to get lock of other as they have been acquired by themselves .
Now according to code both of them will free their own lock ( as they could not get other's lock.) and return false from impendingBow() and both will print
else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
and then again the same thing.
Wont this process run indefinitely with no one bowing to each other ever?
Class BowLoop has infinite loop with a random delay (Thread.sleep(random.nextInt(10));) which prevents scenario that you described. It is a common practice to use random delay before reattempting to get locks after release in case of "collisions".

Can't relase the lock with notify

I've got a test on java thread coding but i have some basic problem.. after hours of trying and searching I decided to try there!
I can't understand why my wait is still locked even after my notify :
Here you can find my code:
public class Mymain {
public static void main(String[] args) {
for( int i=0;i<100;i++){
new ThreadClass(i).start();
}
}
}
public class ThreadClass extends Thread {
static boolean ok = false;
int id;
public ThreadClass(int i) {
id = i;
}
public void run() {
System.out.println("Thread start " + id);
Last.toDo(id);
if (id == 5)
try {
waiting();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (id != 5)
awaking();
System.out.println("thread end " + id);
}
private synchronized void awaking() {
// TODO Auto-generated method stub
if (ok) {
System.out.println("i'm " + id + " and i'm Awaking 5");
ok = false;
notify();
System.out.println("I did the notify and i'm " + id);
}
}
private synchronized void waiting() throws InterruptedException {
System.out.println("Sleeping");
ok = true;
wait();
System.out.println("Awake 5");
}
}
Result
Then it starts looping or it goes in dead lock not sure.. it should just stop the thread with id=5 and then the next thread should re-start the id = 5.. but thread 5 never wake up after the notify...
In the result as you can see I got 2 threads trying to wake up the thread 5 and thread 5 is always waiting since the start^^
The issue is that you are not calling notify() on the same object that you called wait() on. In particular, thread 5 is calling wait() on itself, but thread 8, for example, is calling notify() on itself, not on thread 5. As a result, thread 5 is never getting notified.
Also, you need to make the ok variable volatile to ensure that when one thread sets it, the other threads can see the change. This isn't causing you a problem in this particular case, but it could cause a problem in other cases.
Why you don't use notifyAll() method? When you invoke notify(), it means that only one thread will change a status from waiting to runnable, but there can be the situations when you have more than one thread and other threads which are waiting in the line as well, they will not receive this notification. In my opinion it is preferable to use notifyAll.
i can't understand why my wait is still locked even after my notify :
Wait and notify work when the same object instance is used. If you for example have:
String x1 = "...";
String x2 = "...";
and thread #1 does:
synchronized (x1) { x1.wait(); }
and thread #2 then does:
synchronized (x2) { x2.wait(); }
Then thread #1 will still be waiting because the notify was only for x2. In your example, the thread with id 5 is waiting on its own instance of ThreadClass since you are using method synchronization. Then when other threads call awaking() they too are calling notify on their instances of ThreadClass. If you want thread #5 to see the other thread's notify then they should share a lock object.
Maybe something like:
final Object lock = new Object();
for (int id = 0; id < 100; id++){
new ThreadClass(id, lock).start();
}
...
public class ThreadClass extends Thread {
private final Object lock;
...
public ThreadClass(int id, Object lock) {
this.id = id;
this.lock = lock;
}
...
private void awaking() {
...
synchronized (lock) {
lock.notify();
}
...
}
private void waiting() throws InterruptedException {
...
synchronized (lock) {
lock.wait();
}
...
}
}
Look I did a few changes to your code:
You can't just notify() , you'll notify to this. And you can't just wait() , you'll wait forever. You have to use these function over an Object, so i added an Integer object (just to show you - you'll have to choose the right object).
You have yo understand between synchronized and static synchronized. A quick search would lead you to a perfect answer.
Why function waiting() is synchronized? only thread number 5 calls it.
When calling to an Object.notify() / Object.wait(), you have to declare a synchronized block over the object.
Here's some code:
public class Threads {
public static void main(String[] args) {
Integer intObject = new Integer(0);
for( int i=0;i<100;i++){
new ThreadClass(i, intObject).start();
}
}
}
class ThreadClass extends Thread {
static boolean ok = false;
int id;
Integer intObject;
public ThreadClass(int i, Integer intObject) {
id = i;
this.intObject = intObject;
}
public void run() {
System.out.println("Thread start " + id);
//Last.toDo(id);
if (id == 5)
waiting();
else
awaking(this);
System.out.println("thread end " + id);
}
private static synchronized void awaking(ThreadClass t) {
if(ok) {
System.out.println("i'm " + t.id + " and i'm Awaking 5");
ok = false;
synchronized (t.intObject) {
t.intObject.notify();
}
System.out.println("I did the notify and i'm " + t.id);
}
}
private void waiting(){
System.out.println("Sleeping");
ok = true;
synchronized (intObject) {
try {
intObject.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Awake 5");
}
}

Notify not waking waiting threads

This is my Class. I am using a Quartz scheduler and in that once a job is toBeExecuted, I wanted to avoid concurrency..hence used Synchronize keyword.. and used wait for each thread but it seems that once job is executed..Notify doesnt call the waiting thread ..please help...stuck on this from last two days:
public class SJobListener implements JobListener {
public static final String LISTENER_NAME = "SchedulerJobListener";
ExecutingClass compSched = new ExecutingClass();
#Override
public String getName() {
return LISTENER_NAME; //must return a name
}
// Run this if job is about to be executed.
#Override
public void jobToBeExecuted(JobExecutionContext context) {
String jobName = context.getJobDetail().getKey().toString();
System.out.println("jobToBeExecuted");
System.out.println("Listener : Job : " + jobName + " is going to start...");
System.out.println("Thread running in jobToBeExecuted :"+Thread.currentThread().getName()+" "+Thread.currentThread().getId());
synchronized (compSched) {
if(!condition)
try {
System.out.println("Going to Wait");
Thread.currentThread().wait(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//Run this after job has been executed
#Override
public void jobWasExecuted(JobExecutionContext context,
JobExecutionException jobException) {
System.out.println("jobWasExecuted");
String jobName = context.getJobDetail().getKey().toString();
System.out.println("Listener :Job : " + jobName + " is finished...");
System.out.println("Thread running in jobWasExecuted :"+Thread.currentThread().getName()+" "+Thread.currentThread().getId());
//synchronized (compSched) {
System.out.println("Notifying waiting threads");
//context.notifyAll();
Thread.currentThread().notifyAll();
if (!jobException.getMessage().equals("")) {
System.out.println("Exception thrown by: " + jobName
+ " Exception: " + jobException.getMessage());
jobException.printStackTrace();
}
System.out.println("Out Of jobWasExecuted");
}
}
Thanks in advance.
Please read on java concurrency:
Threads wait on a lock. This lock is what is used to notify other threads waiting on the same lock.
Consider:
public class SynchronizedExample{
private final Object LOCK = new Object();
public void doSomethingOr() {
if(somethingIsNotDone()) {
synchronize(LOCK) {
LOCK.wait(); //trycatch here
}
}
}
public void somethingSone() {
somethingIsDone = true;
synchronized(LOCK) {
LOCK.notifyAll(); //trycatch
}
}
}
Replace Thread.currentThread().wait(200); with compSched.wait(200).
And in jobWasExecuted you should call notify on compSched
The methods jobToBeExecuted and jobWasExecuted are running in different threads so you are waiting on a different object and expecting notifications on a different object. That is why it does not work.
If you explained your requirements a bit more succinctly, a different solution could be provided other than wait notify mechanism.

Where does deadlock happen in this code? Java [duplicate]

This question already has answers here:
How does synchronized work in Java
(4 answers)
Closed 9 years ago.
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
The online tutorial says
When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack. Neither block will ever end, because each thread is waiting for the other to exit bow.
But I don't see any interdependency here. Can anyone explain where the deadlock is?
It's a classical deadlock, 2 threads + 2 locks.
1) Thread 1 locks alphonse and moves to lock gaston
2) Thread 2 locks gaston and moves to lock alphonse
3) Thread 1 reaches gaston but it is locked by Thread 2 and Thread1 blocks
4) Thread 2 reaches alphonse but it is locked by Thread 1 and it blocks
add a delay here to increase probability
public synchronized void bow(Friend bower) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
...

Write a program that will surely go into deadlock [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I recently got this questions asked in an interview.
I answered that deadlock occurs if the interleaving goes wrong, but the interviewer insisted that a program that will always go into deadlock regardless of interleaving can be written .
Can we write such a program ? Can you point me to some example program like that ?
UPDATE: This question was the subject of my blog in January 2013. Thanks for the great question!
How can we write a program that will always go into deadlock no matter how the threads are scheduled?
Here's an example in C#. Note that the program appears to contain no locks and no shared data. It has only a single local variable and three statements, and yet it deadlocks with 100% certainty. One would be hard-pressed to come up with a simpler program that deadlocks with certainty.
Exercise to the reader #1: explain how this deadlocks. (An answer is in the comments.)
Exercise to the reader #2: demonstrate the same deadlock in Java. (An answer is here: https://stackoverflow.com/a/9286697/88656)
class MyClass
{
static MyClass()
{
// Let's run the initialization on another thread!
var thread = new System.Threading.Thread(Initialize);
thread.Start();
thread.Join();
}
static void Initialize()
{ /* TODO: Add initialization code */ }
static void Main()
{ }
}
The latch here ensure that both locks are held when each thread tries to lock the other:
import java.util.concurrent.CountDownLatch;
public class Locker extends Thread {
private final CountDownLatch latch;
private final Object obj1;
private final Object obj2;
Locker(Object obj1, Object obj2, CountDownLatch latch) {
this.obj1 = obj1;
this.obj2 = obj2;
this.latch = latch;
}
#Override
public void run() {
synchronized (obj1) {
latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException();
}
synchronized (obj2) {
System.out.println("Thread finished");
}
}
}
public static void main(String[] args) {
final Object obj1 = new Object();
final Object obj2 = new Object();
final CountDownLatch latch = new CountDownLatch(2);
new Locker(obj1, obj2, latch).start();
new Locker(obj2, obj1, latch).start();
}
}
Interesting to run jconsole, which will correctly show you the deadlock in the Threads tab.
Deadlock happens when threads (or whatever your platform calls its execution units) acquire resources, where each resource can only be held by one thread at a time, and holds on to those resources in a such a way that the holds cannot be preempted, and there exists some "circular" relationship between the threads such that each thread in the deadlock is waiting to acquire some resource held by another thread.
So, an easy way to avoid deadlock is to give some total ordering to resources and impose a rule that resources are only ever acquired by threads in order. Conversely, a deadlock can be intentionally created by running threads that acquire resources, but do not acquire them in order. For example:
Two threads, two locks. The first thread runs a loop that attempts to acquire the locks in a certain order, the second thread runs a loop that attempts to acquire the locks in the opposite order. Each thread releases both locks after successfully acquiring the locks.
public class HighlyLikelyDeadlock {
static class Locker implements Runnable {
private Object first, second;
Locker(Object first, Object second) {
this.first = first;
this.second = second;
}
#Override
public void run() {
while (true) {
synchronized (first) {
synchronized (second) {
System.out.println(Thread.currentThread().getName());
}
}
}
}
}
public static void main(final String... args) {
Object lock1 = new Object(), lock2 = new Object();
new Thread(new Locker(lock1, lock2), "Thread 1").start();
new Thread(new Locker(lock2, lock1), "Thread 2").start();
}
}
Now, there have been a few comments in this question that point out the difference between the likelihood and the certainty of deadlock. In some sense, the distinction is an academic issue. From a practical standpoint, I'd certainly like to see a running system that doesn't deadlock with the code I've written above :)
However, interview questions can be academic at times, and this SO question does have the word "surely" in the title, so what follows is a program that certainly deadlocks. Two Locker objects are created, each is given two locks and a CountDownLatch used to synchronize between the threads. Each Locker locks the first lock then counts down the latch once. When both threads have acquired a lock and counted down the latch, they proceed past the latch barrier and attempt to acquire a second lock, but in each case the other thread already holds the desired lock. This situation results in a certain deadlock.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CertainDeadlock {
static class Locker implements Runnable {
private CountDownLatch latch;
private Lock first, second;
Locker(CountDownLatch latch, Lock first, Lock second) {
this.latch = latch;
this.first = first;
this.second = second;
}
#Override
public void run() {
String threadName = Thread.currentThread().getName();
try {
first.lock();
latch.countDown();
System.out.println(threadName + ": locked first lock");
latch.await();
System.out.println(threadName + ": attempting to lock second lock");
second.lock();
System.out.println(threadName + ": never reached");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(final String... args) {
CountDownLatch latch = new CountDownLatch(2);
Lock lock1 = new ReentrantLock(), lock2 = new ReentrantLock();
new Thread(new Locker(latch, lock1, lock2), "Thread 1").start();
new Thread(new Locker(latch, lock2, lock1), "Thread 2").start();
}
}
Here is a Java example by following Eric Lippert's one:
public class Lock implements Runnable {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public void run() {
Lock lock = new Lock();
}
}
Here is an Example from the documentation:
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
I've rewritten Yuriy Zubarev's Java version of the deadlock example posted by Eric Lippert: https://stackoverflow.com/a/9286697/2098232 to more closely resemble the C# version. If the Java's initialization block works similarily to C# static constructor and first acquires the lock we don't need another thread to also invoke the join method to get a deadlock, it only needs to invoke some static method from Lock class, like the original C# example. Resulting deadlock seems to confirm this.
public class Lock {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Runnable(){
#Override
public void run() {
Lock.initialize();
}
});
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public static void initialize(){
System.out.println("Initializing");
}
}
It's not a simplest interview task you can get: in my project, it paralysed a team's work for a whole day. It's very easy to make your program stop, but it's very hard to get it to the state where thread dump writes something like,
Found one Java-level deadlock:
=============================
"Thread-2":
waiting to lock monitor 7f91c5802b58 (object 7fb291380, a java.lang.String),
which is held by "Thread-1"
"Thread-1":
waiting to lock monitor 7f91c6075308 (object 7fb2914a0, a java.lang.String),
which is held by "Thread-2"
Java stack information for the threads listed above:
===================================================
"Thread-2":
at uk.ac.ebi.Deadlock.run(Deadlock.java:54)
- waiting to lock <7fb291380> (a java.lang.String)
- locked <7fb2914a0> (a java.lang.String)
- locked <7f32a0760> (a uk.ac.ebi.Deadlock)
at java.lang.Thread.run(Thread.java:680)
"Thread-1":
at uk.ac.ebi.Deadlock.run(Deadlock.java:54)
- waiting to lock <7fb2914a0> (a java.lang.String)
- locked <7fb291380> (a java.lang.String)
- locked <7f32a0580> (a uk.ac.ebi.Deadlock)
at java.lang.Thread.run(Thread.java:680)
So the goal would be to get a deadlock which JVM will consider a deadlock. Obviously, no solution like
synchronized (this) {
wait();
}
will work in that sense, even though they will indeed stop forever. Relying on a race condition is not a good idea, either, as during interview you usually want to show something provably working, not something which should work most of the time.
Now, the sleep() solution is okay in a sense it's hard to imagine a situation where it doesn't work, but not fair (we're in a fair sport, aren't we?). The solution by #artbristol (mine is the same, just different objects as monitors) is nice, but long and uses the new concurrency primitives to get the threads in the the right state, which is not that much fun:
public class Deadlock implements Runnable {
private final Object a;
private final Object b;
private final static CountDownLatch latch = new CountDownLatch(2);
public Deadlock(Object a, Object b) {
this.a = a;
this.b = b;
}
public synchronized static void main(String[] args) throws InterruptedException {
new Thread(new Deadlock("a", "b")).start();
new Thread(new Deadlock("b", "a")).start();
}
#Override
public void run() {
synchronized (a) {
latch.countDown();
try {
latch.await();
} catch (InterruptedException ignored) {
}
synchronized (b) {
}
}
}
}
I do recall that the synchronized-only solution fits 11..13 lines of code (excluding comments and imports), but have yet to recall the actual trick. Will update if I do.
Update: here's an ugly solution on synchronized:
public class Deadlock implements Runnable {
public synchronized static void main(String[] args) throws InterruptedException {
synchronized ("a") {
new Thread(new Deadlock()).start();
"a".wait();
}
synchronized ("") {
}
}
#Override
public void run() {
synchronized ("") {
synchronized ("a") {
"a".notifyAll();
}
synchronized (Deadlock.class) {
}
}
}
}
Note we replace a latch with an object monitor (using "a" as an object).
This C# version, I guess java should be pretty similar.
static void Main(string[] args)
{
var mainThread = Thread.CurrentThread;
mainThread.Join();
Console.WriteLine("Press Any key");
Console.ReadKey();
}
import java.util.concurrent.CountDownLatch;
public class SO8880286 {
public static class BadRunnable implements Runnable {
private CountDownLatch latch;
public BadRunnable(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " starting");
synchronized (BadRunnable.class) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired the monitor on BadRunnable.class");
latch.countDown();
while (true) {
try {
latch.await();
} catch (InterruptedException ex) {
continue;
}
break;
}
}
System.out.println("Thread " + Thread.currentThread().getId() + " released the monitor on BadRunnable.class");
System.out.println("Thread " + Thread.currentThread().getId() + " ending");
}
}
public static void main(String[] args) {
Thread[] threads = new Thread[2];
CountDownLatch latch = new CountDownLatch(threads.length);
for (int i = 0; i < threads.length; ++i) {
threads[i] = new Thread(new BadRunnable(latch));
threads[i].start();
}
}
}
The program always deadlocks because each thread is waiting at the barrier for the other threads, but in order to await the barrier, the thread must be holding the monitor on BadRunnable.class.
There's an example in Java here
http://baddotrobot.com/blog/2009/12/24/deadlock/
Where a kidnapper gets into a deadlock when he refuses to give up the victim until he gets the cash but the negotiator refuses to give up the cash until he gets the victim.
A simple search gave me the following code:
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
Source: Deadlock
Here's sample where one thread holding lock starts another thread which wants the same lock and then starter waits until started finishes... forever:
class OuterTask implements Runnable {
private final Object lock;
public OuterTask(Object lock) {
this.lock = lock;
}
public void run() {
System.out.println("Outer launched");
System.out.println("Obtaining lock");
synchronized (lock) {
Thread inner = new Thread(new InnerTask(lock), "inner");
inner.start();
try {
inner.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class InnerTask implements Runnable {
private final Object lock;
public InnerTask(Object lock) {
this.lock = lock;
}
public void run() {
System.out.println("Inner launched");
System.out.println("Obtaining lock");
synchronized (lock) {
System.out.println("Obtained");
}
}
}
class Sample {
public static void main(String[] args) throws InterruptedException {
final Object outerLock = new Object();
OuterTask outerTask = new OuterTask(outerLock);
Thread outer = new Thread(outerTask, "outer");
outer.start();
outer.join();
}
}
Here is an example:
two threads are running , each one waiting for other to release lock
public class ThreadClass extends Thread{
String obj1,obj2;
ThreadClass(String obj1,String obj2){
this.obj1=obj1;
this.obj2=obj2;
start();
}
public void run(){
synchronized (obj1) {
System.out.println("lock on "+obj1+" acquired");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("waiting for "+obj2);
synchronized (obj2) {
System.out.println("lock on"+ obj2+" acquired");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Running this would lead to deadlock:
public class SureDeadlock {
public static void main(String[] args) {
String obj1= new String("obj1");
String obj2= new String("obj2");
new ThreadClass(obj1,obj2);
new ThreadClass(obj2,obj1);
}
}

Categories

Resources