how to resolve deadlock causes by the synchronized method - java

I encountered the issue like the Deadlocks and Synchronized methods. In this case, methodA, methodB, A.last() all must be the synchronized method. So I am going to resolve this issue by removing synchronized in the method B.last(). Any deadlock in this solution? Could you please let me know any solution to resolve this better?
Class A
{
synchronized void methodA(B b)
{
b.last();
}
synchronized void last()
{
System.out.println(“ Inside A.last()”);
}
}
Class B
{
synchronized void methodB(A a)
{
a.last();
}
synchronized void last()
{
System.out.println(“ Inside B.last()”);
}
}
Class Deadlock implements Runnable
{
A a = new A();
B b = new B();
// Constructor
Deadlock()
{
Thread t = new Thread(this);
t.start();
a.methodA(b);
}
public void run()
{
b.methodB(a);
}
public static void main(String args[] )
{
new Deadlock();
}
}

In general, to avoid deadlocks, either use only one lock at all, or make sure that locks are always acquired in the same order.
Assuming that you decide A always has to be locked before B, a minimally invasive bugfix for your example (assuming that nothing else synchronizes against A or B objects) would be this in class B:
void methodB(A a) {
synchronized(a) {
synchronized(this) {
// do whatever was in methodB before, including...
a.last();
}
}
}
That way, if both locks are required, lock of A is always acquired first, causing no deadlocks.
You can also do the same with the Java 5+ java.util.concurrent locks. Removing a synchronized where not needed is of course also an option to solve the deadlock (but if synchronization was needed, it will cause race conditions instead which are usually worse than a deadlock).

You can use a common mutex such as a ReentrantLock or synchronized blocks between the two methods instead of synchronized.
ReentrantLock example:
Class A
{
A(Lock lock) {
this.lock = lock;
}
private Lock lock;
void methodA(B b)
{
lock.lock();
try {
b.last();
} finally {
lock.unlock();
}
}
void last()
{
lock.lock();
try {
System.out.println(“ Inside A.last()”);
} finally {
lock.unlock();
}
}
}
Class B
{
B(Lock lock) {
this.lock = lock;
}
private Lock lock;
void methodB(A a)
{
lock.lock();
try {
a.last();
} finally {
lock.unlock();
}
}
void last()
{
lock.lock();
try {
System.out.println(“ Inside B.last()”);
} finally {
lock.unlock();
}
}
}
Class Deadlock implements Runnable
{
Lock lock = new ReentrantLock();
A a = new A(lock);
B b = new B(lock);
// Constructor
Deadlock()
{
Thread t = new Thread(this);
t.start();
a.methodA(b);
}
public void run()
{
b.methodB(a);
}
public static void main(String args[] )
{
new Deadlock();
}
}
synchronized block example:
Class A
{
A(Object lock) {
this.lock = lock;
}
private Object lock;
void methodA(B b)
{
synchronized(lock){
b.last();
}
}
void last()
{
synchronized(lock){
System.out.println(“ Inside A.last()”);
}
}
}
Class B
{
B(Object lock) {
this.lock = lock;
}
private Object lock;
void methodB(A a)
{
synchronized(lock){
a.last();
}
}
void last()
{
synchronized(lock){
System.out.println(“ Inside B.last()”);
}
}
}
Class Deadlock implements Runnable
{
Object lock = new Object();
A a = new A(lock);
B b = new B(lock);
// Constructor
Deadlock()
{
Thread t = new Thread(this);
t.start();
a.methodA(b);
}
public void run()
{
b.methodB(a);
}
public static void main(String args[] )
{
new Deadlock();
}
}

Related

Why am I getting IllegalMonitorStateException with this code?

I have 2 threads, one calls get() method, another put() method.
I need to synchronize this methods in order to see result of get only after put. I do know how to do this other way, but I want to understand why am i getting .IllegalMonitorStateException with this code.
public class TransferObject {
private int value;
protected volatile boolean isValuePresent = false; //use this variable
public synchronized int get() {
synchronized (TransferObject.class) {
System.out.println("Got: " + value);
notify();
}
return value;
}
public void put(int value) {
synchronized (TransferObject.class) {
this.value = value;
System.out.println("Put: " + value);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Here is example of 2 threads.
public class ConsumerTask implements Runnable {
private TransferObject transferObject;
protected volatile boolean stopped;
public ConsumerTask(TransferObject transferObject) {
this.transferObject = transferObject;
new Thread(this, "ConsumerTask").start();
}
public void run() {
while (!stopped) {
transferObject.get();
}
}
public void stop() {
stopped = true;
}
}
public class ProducerTask implements Runnable {
private TransferObject transferObject;
protected volatile boolean stopped;
static volatile AtomicInteger i = new AtomicInteger(0);
public ProducerTask(TransferObject transferObject) {
this.transferObject = transferObject;
new Thread(this, "ProducerTask").start();
}
public void run() {
while (!stopped) {
transferObject.put(i.incrementAndGet());
}
}
public void stop() {
stopped = true;
}
}
You have two threads and one object for locking TransferObject.class.
When your thread ConsumerTask gets the lock, object TransferObject.class don't have sleeping threads, and when you call notify() for this monitor you get IllegalMonitorStateException
From the description for method notify:
Wakes up a single thread that is waiting on this object's monitor.
You don't have waiting treads for monitor TransferObject.class

Synchronizing overlapping sets of methods

Imagine a Java class with three methods:
master()
foo()
bar()
I want to synchronize master() and foo() and also master() and bar(), without synchronizing foo() and bar(). It can be done will a separate lock for every pair of synchronized methods, but my actual code has many more than three methods so I was hoping there's a way to do it without so many lock objects.
You are essentially describing a ReadWriteLock. Every two methods are allowed to run simultaneously (a "read lock"), except for master(), which excludes all others (a "write lock"):
public class MyClass {
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock r = rwLock.readLock();
private final Lock w = rwLock.writeLock();
public void master() {
w.lock();
// do stuff
w.unlock();
}
public void foo() {
r.lock();
// do stuff
r.unlock();
}
public void bar() {
r.lock();
// do stuff
r.unlock();
}
}
You can use synchronized on any Object. So, you can create a separate lock for the methods:
public class Lock {
private final Object master_foo = null;
private final Object master_bar = null;
public void master() {
synchronized(master_foo) {
synchronized(master_bar) {
...
}
}
}
public void foo() {
synchronized(master_foo) {
...
}
}
public void bar() {
synchronized(master_bar) {
...
}
}
}
I would go with Mureinik's answer, but just for the heck of it, here's another way you can set up read/write synchronization (untested):
public class Test {
private final Semaphore semaphore = new Semaphore(Integer.MAX_VALUE);
public void master() {
semaphore.acquireUninterruptibly(Integer.MAX_VALUE);
try {
//...
} finally {
semaphore.release(Integer.MAX_VALUE);
}
}
public void foo() {
semaphore.acquireUninterruptibly();
try {
//...
} finally {
semaphore.release();
}
}
public void bar() {
semaphore.acquireUninterruptibly();
try {
//...
} finally {
semaphore.release();
}
}
}

Reentrant lock releases automatically in java

Is there any way can we release the re entrant lock automatically.does not need to unlock in finally block is there any way to achieve this
try{
lock.lock;
}
catch(Exception e){
lock.unlock
}
It can be done with an annotation but using the AutoCloseable is also an option:
import java.util.concurrent.locks.ReentrantLock;
public class LockTry {
public static void main(String[] args) {
new LockTry().testWithLock();
}
private void testWithLock() {
ReentrantLock lock = new ReentrantLock();
try (CloseableLock clock = new CloseableLock(lock)) {
System.out.println("run with lock");
}
}
static class CloseableLock implements AutoCloseable {
private final ReentrantLock lock;
CloseableLock(ReentrantLock lock) {
super();
this.lock = lock;
lock.lock();
System.out.println("locked");
}
#Override
public void close() {
lock.unlock();
System.out.println("unlocked");
}
}
}

Java method synchronization improper usage?

Suppose there is the following code:
class MyClass {
synchronized void myMethod1() {
//code
}
synchronized void myMethod2() {
//code
}
}
Now suppose myMethod1() and myMethod2() access distinct data; now if there are two threads, thread A calling only myMethod1() and thread B calling only myMethod2().
If thread A is executing myMethod1(), will thread B block waiting on myMethod2() even if they don't access the same data and there is no reason for this? As far as I know, synchronized methods use the monitor of this object for instance methods and that of MyClass.class object for static functions.
Your understanding of the situation is correct.
The typical solution is to have separate dedicated lock objects for the resources in question.
class MyClass {
private final Lock lock1 = new ReentrantLock();
private final Lock lock2 = new ReentrantLock();
void myMethod1() {
lock1.lock();
try {
//code
} finally {
lock1.unlock();
}
}
void myMethod2() {
lock2.lock();
try {
//code
} finally {
lock2.unlock();
}
}
}
You are correct in all your suppositions. In the case where no data is in common then there is no reason to synchronize at the method level.
The sychronized method will lock on the object itself. So each method will have to wait for the other to finish its access to release the object. If your methods are truly accessing distinct data you can do something like this:
class MyClass {
private static Object mLock1 = new Object();
private static Object mLock2 = new Object();
void myMethod1() {
synchronized(mLock1) {
//code
}
}
void myMethod2() {
synchronized(mLock2) {
//code
}
}
}
And you can then access them independently.
edit: You can essentially think of synchronized methods as being equivalent to this:
void myMethod1() {
synchronized(this) {
//your code
}
}
Shown like this it is pretty clear why two synchronized methods block each other because they have to wait for the lock on this to free.
Yes, declaring both methods as synchronized will make them block each other, even if they access different data elements.
To avoid this, you can use a more fine grained locks. E.g.:
class MyClass {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
void myMethod1() {
synchronized (lock1) {
//code
}
}
void myMethod2() {
synchronized (lock2) {
//code
}
}
You can use different monitors for myMethod1 and myMethod2 as follows:
class MyClass {
Object monitor1 = new Object();
Object monitor2 = new Object();
void myMethod1() {
synchornized(monitor1) {
//code
}
}
void myMethod2() {
synchronized(monitor2) {
//code
}
}
}

IllegalMonitorStateException raised with explicit lock/condition

I want to have such kind of work flow using explicit lock/condition variables (It's a course project which mandates this style.): A is the main class, it asks B to do some job from time to time. B has a worker class C which constantly queries B about new jobs to do and do it. After C finishes, it will call A's callback function to notify A the job is done.
However when I try to run the program, I get an IllegalMonitorStateException, when the callback() is trying to notify the doit() function.
exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at Test$A.callback(Test.java:49)
at Test$C.run(Test.java:115)
I looked at the javadoc and some Q&A about this exception, but still no idea why I get this.
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class Test {
public class A
{
private ReentrantLock lock;
private Condition cond;
private boolean bool;
private B b;
public A()
{
this.lock = new ReentrantLock();
this.cond = lock.newCondition();
b = new B(this);
bool = false;
}
public void doit()
{
try {
lock.lock();
b.letgo();
while (!bool) {
System.out.println("A::doit() Block.");
cond.awaitUninterruptibly();
}
System.out.println("A::doit() Done.");
}
finally {
lock.unlock();
}
}
public void callback() {
try {
lock.lock();
bool = true;
cond.notify();
System.out.println("A::callback() done.");
}
finally {
lock.unlock();
}
}
}
public class B
{
private C c;
private ReentrantLock lock;
private Condition cond;
private boolean bool;
public B(A a)
{
this.lock = new ReentrantLock();
this.cond = lock.newCondition();
bool = false;
c = new C(a, this);
c.start();
}
public void letgo()
{
try {
lock.lock();
bool = true;
}
finally {
lock.unlock();
}
}
public void get()
{
try {
lock.lock();
while (!bool) {
cond.awaitUninterruptibly();
}
bool = false;
return;
}
finally {
lock.unlock();
}
}
}
public class C extends Thread
{
private A a;
private B b;
public C(A a, B b)
{
this.a = a;
this.b = b;
}
public void run()
{
while (true) {
b.get();
a.callback();
}
}
}
public static void main(String args[])
{
Test t = new Test();
t.test1();
}
public void test1()
{
A a = new A();
a.doit();
}
}
Use the signal() method on Condition in place of notify().
While you can successfully synchronize on a Condition instance, and then use the traditional wait() and notify() methods, you might as well just use an Object if you aren't using the extended capabilities of the concurrent classes.
Condition was intended to be used with the equivalent methods await() and signal(), and their enhanced variants.

Categories

Resources