A Mutex for inter-threading usages in Java? - java

I want a Mutex in Java which let me to wait on it in a thread and release it in another thread. I know that I can use a Semaphore with capacity of 1 but the problem is that the "acquire()" method throws "InterruptedException". Is there any special synchronization way for this purpose in Java?

Luckily, Semaphore provides this method for you :)
public void acquireUninterruptibly()
Acquires a permit from this semaphore, blocking until one is
available. Acquires a permit, if one is available and returns
immediately, reducing the number of available permits by one.
If no permit is available then the current thread becomes disabled for
thread scheduling purposes and lies dormant until some other thread
invokes the release() method for this semaphore and the current thread
is next to be assigned a permit.
If the current thread is interrupted while waiting for a permit then
it will continue to wait, but the time at which the thread is assigned
a permit may change compared to the time it would have received the
permit had no interruption occurred. When the thread does return from
this method its interrupt status will be set.

InterruptedException is not an issue, just wrap it in a loop:
while(true) {
try {
semaphore.acquire();
break;
} catch(InterruptedException e) {
//swallow, continue;
}
}
However this code is not very safe and elegant, but will work providing that you "want to make sure you can acquire a permit!"

if you have a code in which a thread is going to wait then you will definitely have to handle interrupted exception unless you are using synchronized block. Also, What is the problem with interrupted exception?

ThreadA
volatile boolean waitCondition = true
synchronized(lockObject) {
while (waitContidion) {
lockObject.wait();
}
}
ThreadB
synchronized(lockObject) {
waitCondition = false;
lockObject.notifyAll();
}
or use Condition/Signal on Lock instances.
Correct handling of InterruptedException is very important, at least you must set it's interrupted flag with Thread.currentThread().interrupt() method in catch block.

Related

Can't understand this multi-threading exception behavior

According to the documentation for ReentrantLock.newCondition(), the calling thread needs to own a lock before calling a signaling method:
If this lock is not held when any of the Condition waiting or signalling methods are called, then an IllegalMonitorStateException is thrown.
Indeed, this is what I see when I try it:
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signalAll(AbstractQueuedSynchronizer.java:1954)
at PingPongPrinter_.printPing(PingPong2.java:35)
at WorkerPing.run(PingPong2.java:53)
at java.lang.Thread.run(Thread.java:748)
So why do this restriction exists in java.util.concurrent.locks.ReentrantLock? I believe there is no such restriction in C++.
Answer to original question
You're unlocking a lock associated with the condition before signaling it.
From documentation:
An implementation may (and typically does) require that the current thread hold the lock associated with this Condition when this method is called. Implementations must document this precondition and any actions taken if the lock is not held. Typically, an exception such as IllegalMonitorStateException will be thrown.
Also, only lock for the time required to modify the value you are conditioning for.
void printPong() throws Exception {
// wait for pong condition
while (isPing) {
blockPong.await();
}
rlock.lock();
isPing = true; // modify value
blockPing.signalAll(); // signal ping
rlock.unlock();
System.out.println("Pong");
}
void printPing() throws Exception {
// wait for ping condition
while (!isPing) {
blockPing.await();
}
rlock.lock();
isPing = false; // modify value
blockPong.signalAll(); // signal pong
rlock.unlock();
System.out.println("Ping");
}
Answer to modified question
So why do this restriction exists in java.util.concurrent.locks.ReentrantLock? I believe there is no such restriction in C++.
Because ReentrantLock is mutually exclusive. It provides access to one single thread at any given time. That's a design choice.
In C++ the std::condition_variable also requires you to own a mutex to the resource in order to signal.

Guarded Suspension in Java

Based on tutorials online, I have come up with below code of guarded suspension.
public synchronized String method1() throws InterruptedException {
lock = true;
Thread.sleep(17000);
lock = false;
notifyAll();
return "Method1";
}
public synchronized String method2() throws InterruptedException {
while(lock) {
wait();
}
Thread.sleep(3000);
return "From Method 2";
}
Above two methods are called at the same time from multiple threads.
From the above example, Does that lock variable used in the pre-condition for wait() ever be true ?
because with use of synchronized keyword, both methods are executed mutually exclusively.
Is the above example correct for Guarded suspension ?
When do we need Guarded Suspension ?
The Java keyword synchronized used on an instance method does ensure that only one thread at a time will execute any method on that single instance having the method modifier synchronized as well. More precise: not only on any method but on any resource / data using the same instance as a monitor or semaphore for mutual exclusively access control.
In your example, both instance methods have the modifier synchronized and hence will ensure only one thread is executing code inside any of those methods at any given time.
The variable lock is of no use in your example, because the same method which sets it to true does change it back to false. Hence method2 will never observe lock to be true.
Whenever more than one thread have to operate on a mutable resource and both threads should agree on the state read / operated, you have to protect this resource from racing conditions (read or modified concurrently). Otherwise the result may be different if executed by a single thread.
I think, your implementation is incorrect because you are doing lock = true; and lock = flase; in the same method.
In my opinion, it has to be done like below,
public synchronized String method1() throws InterruptedException {
Thread.sleep(17000);
lock = false;
notifyAll();
return "Method1";
}
public synchronized String method2() throws InterruptedException {
while(lock) {
wait();
}
Thread.sleep(3000);
lock = true;
return "From Method 2";
}
You have to understand that Guarded Suspension is a pattern when you have a situation where a precondition also needs to be satisfied in addition to synchronization lock being available.
e.g. when going to implement a thread-safe blocking queue, we need to put take() method thread on wait state if no items are available and put method thread also on wait state if queue is full. So this requirement is there in addition to synchronized access i.e. queue needs to be accessed in mutual exclusive way ( that is a primary requirement so you put synchronized on method signature ) but if queue is not in a proper state( by checking precondition variable) , you do wait or notify etc.
You have to also keep in mind that Thread.sleep(...) doesn't releases synchronization lock while Object.wait() does.
Take a real - life example ( like that of a thread - safe blocking queue ) then we can tell if your implementation is correct or not - its not possible to tell if your implementation is correct or not ( other than pointing that lock shouldn't be set / reset in same method ) since there is no generic implementation of this pattern.
Refer This
Hope it helps !!

Guarded blocks -- notifyAll() vs interrupt()

This Q looks for verification and/or comments/opinions the following:
The example on Guarded Blocks is as follows:
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
The other end of this code-- the one setting joy properly is something like this:
public void setJoy2(TheClass t) {
synchronized (t) {
t.joy = true;
t.notifyAll();
}
}
The above does the "signaling" on joy by the use of notify().
An alternative is managing this "signalling" by interrupt():
public void guardedJoy2() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
synchronized(this) {
try {
wait();
} catch (InterruptedException e) {}
}
}
System.out.println("Joy and efficiency have been achieved!");
}
and the one setting joy and letting the thread waiting for it is:
public void setJoy2(TheClass t) {
t.joy = true;
t.interrupt();
}
I'm looking to make a comparison between the two-- setJoy() and setJoy2().
First of all, guardedJoy2() above can "hear" both setJoy() and setJoy2() properly-- can see when joy is set and act the way it is expected to(?)
How does guardedJoy2() compare to guardedJoy()?
It achieves does the same thing as guardedJoy()-- i might be missing something, but i'm not seeing a difference in the outcome. The only difference is that guardedJoy2() released the lock of this from within the loop, and someone else acquire it before the method terminates for some unexpected results. Setting that aside (i.e., assuming that this is the only place where the use of joy and its side effects appear in the code), there's not difference between guardedJoy() and guardedJoy2()(?)
guardedJoy2() responds to both setJoy() and setJoy2().
It can "hear" from setJoy() when it is done, re-acquires its lock and go from there.
And, it can "hear" from setJoy2()-- by receiving the interrupt and thus throwing InterruptedException to get out of wait(), that's also the end of synch'd statement, checks to see in while condition that joy is set and goes from there. If the interrupt was from "someone" else and not from the one setting joy, gets into the loop again the same way till joy is set.
When, wait() is invoked and thus the lock of this is released in guardedJoy2(),
some other thread can get in by acquiring this lock and do things that are not supposed to be done till joy is set and guardedJoy2() is supposed to return properly. However, setting this aside (again, assuming this isn't an issue-- the only thing being looked for is seeing that message on the last line of guardedJoy2() on the console.) This-- setJoy2() can be preferable in cases where other things can be done on the object while it's getting its joy set and go from there (in setJoy2(), the thread setting joy doesn't have to have the lock of the object to interrupt it while setJoy() should have that lock to invoke notifyAll() on it).
How does guardedJoy2() & setJoy2() compare to guardedJoy() & setJoy() above?
TIA.
I'm going of the assumption that you meant just notify() in your first setJoy rather than notifyAll().
First, it's important to note that if you're invoking interrupt() on an expression of type TheClass, then TheClass is a subclass of Thread. This goes against a number of -recommendations that state that you should use Runnable instances to encapsulate the logic to be run on a thread rather than subclassing the class Thread. The javadoc of Thread#join(int) also states
It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
This is because some implementations of Java use those methods to handle thread logic behind the scenes. If you do not know that implementation logic and use these methods with Thread instances, you might get undesired behavior.
Then, and this might warrant some profiling, throwing (creating) an exception is an expensive operation, probably more so than removing a Thread from an object's wait set. What's more, exceptions should be used for exceptional conditions, not to guide your application logic.
I was going to say that your second example's synchronization order may be incorrect (assuming joy was not volatile) because the read in the guardedJoy2 loop might not see the write in setJoy2. However, the Java Language Specification states
If thread T1 interrupts thread T2, the interrupt by T1
synchronizes-with any point where any other thread (including T2)
determines that T2 has been interrupted (by having an
InterruptedException thrown or by invoking Thread.interrupted or
Thread.isInterrupted)
So you still have visibility guarantees in place.

Why does 'wait() method within synchronized block' have deadlock possibility?

klocwork JD.LOCK.WAIT issue is reported when an Object.wait() method is called while the method is holding two or more locks.
klocwork says that waiting on a monitor while two locks are held may cause deadlock and the issue should be taken into account.
But I cannot understand why this causes deadlock.
Who can help me understand this issue?
Following code is from klockwork. The JD.LOCK.WAIT issue occurs on line 14 lock.wait();.
String name;
synchronized void waitForCondition(Object lock) {
try {
synchronized(lock) {
name = "aa";
lock.wait(); //line 14
}
} catch (InterruptedException e) {
return;
}
}
Lets say t1 enters the waitForCondition() method. So t1 now has this as a lock. Meanwhile, some other thread has just acquired lock object and is trying call waitForContion().
t2 holds lock but is waiting for this to enter waitForContion().
t1 holds this but is waiting for lock to exit waitForContion().
That is a deadlock. Neither of them can make any progress and are waiting on each other.
To avoid this, one strategy is to make sure any thread has all the resources it needs to complete. Here it means that lock and this can only be acquired together and not otherwise.
Also, when lock.wait() is called, only lock is released while this is not. So, in such a case no thread can call waitForContion() on that object.

Does Java notify waiting threads implicitly?

I wrote a test app that should never stop. It issues t.wait() (t is a Thread object), but I never call notify. Why does this code end?
Despite the main thread synchronizing on t, the spawned thread runs, so it doesn't lock this object.
public class ThreadWait {
public static void main(String sArgs[]) throws InterruptedException {
System.out.println("hello");
Thread t = new MyThread();
synchronized (t) {
t.start();
Thread.sleep(5000);
t.wait();
java.lang.System.out.println("main done");
}
}
}
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
java.lang.System.out.println("" + i);
try {
Thread.sleep(500);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
The result is that the main thread waits 5 seconds and during this time worker gives its output. Then after 5 seconds are finished, the program exits. t.wait() does not wait. If the main thread wouldn't sleep for 5 seconds (commenting this line), then t.wait() would actually wait until the worker finishes. Of course, join() is a method to use here, but, unexpectedly, wait() does the same thing as join(). Why?
Maybe the JVM sees that, since only one thread is running, there is no chance to notify the main thread and solves the deadlock. If this is true, is it a documented feature?
I'm testing on Windows XP, Java 6.
You're waiting on a Thread - and while most objects aren't implicitly notified, a Thread object is notified when the thread terminates. It's documented somewhere (I'm looking for it...) that you should not use wait/notify on Thread objects, as that's done internally.
This is a good example of why it's best practice to use a "private" object for synchronization (and wait/notify) - something which only your code knows about. I usually use something like:
private final Object lock = new Object();
(In general, however, it's cleaner to use some of the higher-level abstractions provided by java.util.concurrent if you can. As noted in comments, it's also a good idea to implement Runnable rather than extending Thread yourself.)
The JavaDoc for wait gives the answer: spurious wakeups are possible. This means the JVM is free to end a call to wait whenever it wants.
The documentation even gives you a solution if you don't want this (which is probably always the case): put the call to wait in a loop and check whether the condition you wait for has become true after every wakeup.

Categories

Resources