Use of notify() and notifyAll() doesn't work in the code - java

I pasted the code below. That is commented enough.
Clear about wait(). When comes here it jumps to another block. That part i am oaky.
My doubt is Why we are using notify and notifyAll(). If you remove these two from below code, it works fine.
class Reader extends Thread{
Calculator c;
//here we didn't write no-arg constructor. Note this.
// one - arg constructor.
public Reader(Calculator calc){
c = calc;
}
public void run(){
synchronized(c){
// 2. Acquiring the object lock and executes this code of block.
try{
System.out.println("Waiting for calculation...");
c.wait();
// 3. Release the object lock and moves to the second synchronize block below
// 6. Later the object get the lock here and moves on.
}catch(InterruptedException e){
}
System.out.println("Total is: "+c.total);
}
}
public static void main(String[] args){
//Instantiating new with no-arg. One more doubt, How this work without no-arg constructor above. Please explain.
Calculator calculator = new Calculator();
//Instantiating new with one-arg
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
// 1. Once you start here it will goto first synchronized code block above
calculator.start();
}
}
class Calculator extends Thread{
int total;
public void run(){
synchronized(this){
// 4. This block acquires that object lock and executes the code block below.
for(int i=0;i<100;i++){
total +=i;
}
// 5. As per documentation, If we give notify() it will release the object lock to only one thread object of its choice.
// If we use notifyAll(); it will release the object lock to all the three thread object.
notify();
// My doubt here is without using the notify or notifyAll it is working fine.
// As per docs if we use notify() only one object should get the lock. That is also not working here.
}
}
}

General comment: the javadoc of Object#wait states that
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop.
So a waiting thread can wake up without being notified and your design should take that into account by waiting in a loop and checking for an exit condition (cf example in the javadoc).
In your case, however, the issue is slightly different. According to the Thread#join 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.
So when your Calculator finishes, it calls this.notifyAll() and wakes up all the waiting threads.
How to fix it?
You should use a separate lock object, similar to: private final Object lock = new Object(); in your Calculator and provide a getter for the Readers.

There is no guarantee about the order in which the threads begin to run. If Calculator runs first then its notify will be lost and no one Reader will be notified.

Here is the corrected version of the above program which makes some sense to notify() and notifyAll().
Here i implemented Runnable instead of extending Threads. Thats the only change i did. Its working perfectly.
class Reader implements Runnable{
Calculator c;
public Reader(Calculator calc){
c = calc;
}
public void run(){
synchronized(c){
try{
System.out.println("Waiting for calculation...");
c.wait();
}catch(InterruptedException e){
}
System.out.println("Total is: "+c.total);
}
}
public static void main(String[] args){
Calculator calculator = new Calculator();
Reader read = new Reader(calculator);
Thread thr = new Thread(read);
Thread thr1 = new Thread(read);
Thread thr2 = new Thread(read);
thr.start();
thr1.start();
thr2.start();
new Thread(calculator).start();
}
}
class Calculator implements Runnable{
int total;
public void run(){
System.out.println("Entered Calculator");
synchronized(this){
for(int i=0;i<20;i++){
total +=i;
}
notifyAll();
}
}
}

Related

Java wait() does not get waked by notify()

Hallo I've been debugging my code for a whole day already, but I just can't see where could be wrong.
I use SerialPortEventListener on a main thread, in a working thread I have a client socket communicating to a server.
Since after this working thread reach return, I still need some wrap up work done in the main thread, i want to create a "pseudothread" that wait in the main thread until the it is notified from the listener onEvent method.
but this pseudothread seems to be waiting forever.
I checked the locked thread pseudoThread, they should have the same object id in the Runnable and in Listener class.
"PseudoThread waiting" got displayed, but PseudoThread awake is never showed.
Console output shows:
PseudoThread waiting
..
..
false notified pseudothread.
PS if I create a lock in Main class with public final Object lock = new Object(); and replace all main.pseudoThread with main.lock, I get java.lang.IllegalMonitorStateException.
private class Pseudo implements Runnable{
Main main;
public Pseudo(Main main) {
this.main = main;
}
#Override
public void run() {
synchronized(main.pseudoThread){
try {
System.out.println("PseudoThread waiting");
main.pseudoThread.wait();
System.out.println("PseudoThread awake");
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}
in main method:
public static void main(String[] args) {
Main main = new Main();
main.initArduino();
//more code. including starting the working thread
main.pseudoThread = new Thread(main.new Pseudo(main));
main.pseudoThread.start();
try {
main.pseudoThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void initArduino() {
arduino = new Arduino(this);
if(!arduino.initialize())
System.exit(1);
}
and in the listener class (which also runs in main thread)
//class constructor;
public Arduino(Main Main){
this.main = Main;
}
//listening method
public void serialEvent(SerialPortEvent oEvent){
//some code to interract with working thread.
record();
}
private void record(){
synchronized(main.pseudoThread){
main.pseudoThread.notify();
System.out.println("notified pseudothread.");
}
}
Without looking too deeply into what might actually be happening, I can see that your use of wait()/notify() is all wrong. Probably you are experiencing a "lost notification." The notify() function does nothing if there is no thread waiting for it at the moment when it is called. If your serialEvent() function calls notify() before the other thread calls wait(), then the notification will be lost.
Consider this example:
class WaitNotify() {
private final Object lock = new Object();
private long head = 0;
private long tail = 0;
public void consumer() {
synchronized (lock) {
while(head == tail) {
lock.wait();
}
doSomething();
count head += 1;
}
}
public void producer() {
synchronized (lock) {
tail += 1;
lock.notify();
}
}
}
The essential points are:
(1) The consumer() function waits for some relationship between data to become true: Here, it waits for head != tail.
(2) The consumer() function waits in a loop. There's two reasons for that: (a) Many programs have more than one consumer thread. If consumer A wakes up from the wait(), there's no guarantee that consumer B hasn't already claimed whatever it was that they both were waiting for. And (b) The Java language spec allows foo.wait() to sometimes return even when foo.notify() has not been called. That's known as a "spurious wakeup." Allowing spurious wakeups (so long as they don't happen too often) makes it easier to implement a JVM.
(3) The lock object is the same lock that is used by the program to protect the variables upon which the condition depends. If this example was part of a larger program, you would see synchronized(lock) surrounding every use of head and tail regardless of whether the synchronized code is wait()ing or notify()ing.
If your own code obeys all three of the above rules when calling wait() and notify(), then your program will be far more likely to behave the way you expect it to behave.
As suggested by james it could be lost notification case or it could be that.. Two Threads 1- Your Main Thread and 2- Pseudo thread Are waiting on the same Thread Instance Lock (main.pseudoThread)( Main thread waits on the same lock by calling join method).
Now you are using notify which wakes the Main thread from join method and not the one
waiting in your Pseudo. To check for the second case try calling notifyall in record this will either
confirm the second case or will rule this possibility.
Anyways please refactor your code not to use synch on Thread instance its bad practice. Go for ReentrantLock or CoundDownLatch something.
Usage of notify and wait seem to be incorrect. Method name notify can be a bit misleading because it is not for general purpose "notifying". These methods are used to control the execution of synchronization blocks. Wait will allow some other thread to synchronize with same object while current threads pauses. Basically this is used when some resource is not available and execution can not continue. On the other hand notify will wake one waiting thread wake from wait after notifying thread has completed its synchronized-block. Only one thread can be in synchronized block of the same object at the same time.
If the idea is just keep the main program running until notified then semaphore would be much more appropriate. Something like this.
public void run() {
System.out.println("PseudoThread waiting");
main.semaphore.acquireUninterruptibly();
System.out.println("PseudoThread awake");
}
//...
private void record(){
main.semaphore.release();
}
//...
public static void main(String[] args) {
main.semaphore = new Semaphore(0);
//...
}

Java - Call wait() on an object and then allow object access to method

I have this method which takes a thread as a parameter. I want this method to be able to make a thread wait if there is not one waiting already and then wake up when another thread comes into the method so that the two of them can interact. I think I'm close but after I call wait() on the first thread no other threads can gain access to that method. Here is a minimalist version of my code:
// In the class 'Node'
public synchronized void trade(Thread thread)
{
if (!threadWaiting)
{
threadWaiting = true;
synchronized(thread)
{
try {
thread.wait();
} catch (InterruptedException e) {...}
}
}
}
I apologise for missing anything obvious, I've been looking around for an answer but I'm new to threading so I've no idea what to look for.
So my problem is that when another thread attempts to get into trade() they can't, the debugger just stops right there.
EDIT:
Here's some more clarification on what I'm asking. I'm afraid I wasn't too clear in my original post.
So I have one class called Node and another class called Bot. Bot extends thread so that it can be paused. At the start of the program multiple Bot objects are created and are then started, each Bot will then call the trade() method of the Node and pass itself to the method. If a Bot is the first in the method then I want its thread to wait on the Node until another Bot comes along (The waiting Bot will be stored in the Node), at which point the two Bots will interact.
Below is a clearer example of my method in pseudo code:
// Variable to hold the bot that is waiting.
private Bot waitingBot = null;
// Method belonging to Node.
public synchronized void trade(Bot currentBot)
{
if (waitingBot == null)
{
waitingBot = currentBot;
waitingBot.wait();
}
else
{
currentBot.interactWith(waitingBot);
waitingBot.notify();
waitingBot = null;
}
}
Sorry about the wording of my original post.
Your implementation has a flaw. You are taking lock on parameter passed which will be different for all Threads so they can't interact with wait notify.
EDIT: I am not sure what exactly your aim is but based on details this might help:
EDIT2: Added lock()
private final Lock lck = new ReentrantLock();
private final Condition cnd = lck.newCondition();
private final AtomicBoolean threadwaiting = new AtomicBoolean(false);
public synchronized void trade(Thread thread)
{
lck.lock();
try{
if(threadwaiting.get()){
cnd.signalAll();
threadwaiting.set(false);
//perform your task
}else{
cnd.await();
threadwaiting.set(true);
}
}
} finally {
lck.unlock()
}
}
EDIT:
Looking at your updated post , you should use cyclicbarrier with count 2 then that should solve it all for you.
This is a dead lock, because when you call thread.wait(); you release thread object lock. But this object lock on synchronized method remains, that's why no one else can enter it.
It's like loki's code, but improved
private final Lock lock = new ReentrantLock();
private final Condition cnd = lock.newCondition();
private final AtomicBoolean threadwaiting = new AtomicBoolean(false);
public void trade(Thread thread) {
lock.lock();
if (threadwaiting.get()) {
cnd.signalAll();
lock.unlock();
// perform your task of second thread
} else {
threadwaiting.set(true);
try {
cnd.await();
// perform your task of first thread
} catch (InterruptedException e) {
} finally {
threadwaiting.set(false);
lock.unlock();
}
}
}

Why does the following code result in thread contention

I have the following code
public class Test {
Lock lock = new ReentrantLock();
public static void main(String args[]) throws Exception {
Test t = new Test();
Second second = t.new Second();
second.lock = t.lock;
Thread thread = new Thread(second);
thread.start();
Thread.sleep(2000);
try {
t.lock.lock();
System.err.println("got the lock");
} finally {
second.shutdown = true;
t.lock.unlock();
}
}
private class Second implements Runnable {
Lock lock;
volatile boolean shutdown = false;
int i = 0;
public void run() {
while (!shutdown) {
try {
lock.lock();
System.out.println("In second:" + i++);
} finally {
lock.unlock();
}
}
}
}
}
I read here that there is a concept of fair and unfair lock, but making locks fair has a big performance impact and nevertheless shouldn't the above code give some fairness to the current thread.
While actual execution of the above code, the second thread runs forever (gave way for main thread after 545342 iterations)
Is there something I am doing wrong here? Can anyone explain this behavior?
Basically without making the lock fair, the second thread is unlocking and managing to reacquire the lock before the first thread gets a chance to do so. After your large number of iterations, it must have been pre-empted between the "unlock" and the "lock", giving your first thread an opportunity to get in and stop it.
Fundamentally though, you simply shouldn't have code like that in the second thread - under what real life situation do you want to repeatedly release and acquire a lock doing no work between the two, beyond checking a flag? (And if you do want to do that, why do you want to require that a "shutting down" thread acquires the same lock in order to set the flag?)

Why is this thread allowing another one to access its synchronized method?

I have the following codes. I expected one thread to execute its synchronized method completely and then allow another one to access the same method. However, this is not the case.
public class Threads {
/**
* #param args
*/
public static void main(String[] args) {
//Thread Th = new Threads();
Thread th = new Thread (new thread1 ());
th.start();
Thread th1 = new Thread (new thread1 ());
th1.start();
}
}
class thread1 implements Runnable{
String name = "vimal";
public void run() {
System.out.println("Runnable "+this.name);
setNAme("Manish");
}
public synchronized void setNAme(String name){
try {
System.out.println("Thread "+Thread.currentThread().getName());
wait(1000);
this.name = name;
System.out.println("Name "+this.name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have one output as
Runnable vimal
Thread Thread-0
Runnable vimal
Thread Thread-1
Name Manish
Name Manish
What is the use of synchronized here and how do I make my method to run completely before another accesses it?
synchronized has no effect here because you are not synchronizing on the same object in both cases. When applied to an instance method, the synchronized keyword causes the method to be synchronized on this. So in each case you are synchronizing on the instance of thread1, and there are two of those.
The more interesting test would be when you run the same instance of thread1 in two threads simultaneously. In that case, calling wait(1000) is a very bad thing to do because (as documented) it releases the lock on this. You want to use Thread.sleep(1000) instead in your code.
If you need to have two instances of thread1, you need to synchronize on some shared object, possibly like this:
private static final Object lockObject = new Object();
public void setName(String newName) {
synchronized(lockObject) {
doSetName(newName);
}
}
You will have to remove the call to wait(1000). It looks like what you actually want is a call to Thread.sleep(1000), if you simply want to pause the current thread, this does not release ownership of any monitors.
From the javadoc for Object.wait().
This method causes the current thread (call it T) to place itself in
the wait set for this object and then to relinquish any and all
synchronization claims on this object. Thread T becomes disabled for
thread scheduling purposes and lies dormant until one of four things
happens:
Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be
awakened.
Some other thread invokes the notifyAll method for this object.
Some other thread interrupts thread T.
The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into
consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and
re-enabled for thread scheduling. It then competes in the usual manner
with other threads for the right to synchronize on the object; once it
has gained control of the object, all its synchronization claims on
the object are restored to the status quo ante - that is, to the
situation as of the time that the wait method was invoked. Thread T
then returns from the invocation of the wait method. Thus, on return
from the wait method, the synchronization state of the object and of
thread T is exactly as it was when the wait method was invoked.
UPDATE: As has been mentioned in other answers, you are not synchronizing on the same object. Once you do, you will still suffer the same output, due to the issue I have mentioned. You will need to fix both for your desired results.
The output is correct, you are creating to independent threads that do not share any data. Thus both threads start with first string, and after some time, the string is changed and printed.
You're creating 2 thread1 objects. They each have their own setNAme method. Synchronized methods only synchronize on the object, not the class. Unless the method is static.
You have two Threads here with independent name variables and independent monitors, so each Thread is only accessing its own members. If you want to have the threads interact with each other you'll have to implement such an interaction.
you are creating two separate thread1 objects and running them. Each thread has it's own copy of the name variable as well as the setName function. Make them both static and you will see the effects of synchronization.
You are locking on two different instance of the objects where you dont need any synchronization at all. You need to synchronize only if you are working on a shared data. I think you meant to write a test like the below.
If you test this, you will realize that the second thread will wait until the first thread is completed with the synchronized method. Then take out the synchronized word and you will see both threads are executing at the same time.
public class SynchronizeTest {
public static void main(String[] args) {
Data data = new Data();
Thread task1 = new Thread(new UpdateTask(data));
task1.start();
Thread task2 = new Thread(new UpdateTask(data));
task2.start();
}
}
class UpdateTask implements Runnable {
private Data data;
public UpdateTask(Data data) {
this.data = data;
}
public void run() {
try {
data.updateData();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Data {
public synchronized void updateData() throws InterruptedException {
for (int i = 0; i < 5; i++) {
Thread.sleep(5000);
System.out.println(i);
}
}
}

Java for newbies - DeadLock imitation

I'm trying to write very simple program which will imitate simple DeadLock, where Thread A waits for Resource A locked by Thread B and Thread B waits for Resource B locked by Thread A.
Here is my code:
//it will be my Shared resource
public class Account {
private float amount;
public void debit(double amount){
this.amount-=amount;
}
public void credit(double amount){
this.amount+=amount;
}
}
This is my runnable which performs Operation on the resource above:
public class BankTransaction implements Runnable {
Account fromAccount,toAccount;
float ammount;
public BankTransaction(Account fromAccount, Account toAccount,float ammount){
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.ammount = ammount;
}
private void transferMoney(){
synchronized(fromAccount){
synchronized(toAccount){
fromAccount.debit(ammount);
toAccount.credit(ammount);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Current Transaction Completed!!!");
}
}
}
#Override
public void run() {
transferMoney();
}
}
and finally my main class:
public static void main(String[] args) {
Account a = new Account();
Account b = new Account();
Thread thread1 = new Thread(new BankTransaction(a,b,500));
Thread thread2 = new Thread(new BankTransaction(b,a,500));
thread1.start();
thread2.start();
System.out.println("Transactions Completed!!!");
}
}
Why does this code run execute successfully and I don't have and deadLock?
It's got the potential for deadlock - but both locks are acquired so quickly together that one thread can get both before the other has the chance to acquire its first one.
Put another Thread.sleep(500); call between the two synchronized statements and it does deadlock: both threads will enter "their" outer lock, sleep, then when they wake up they'll both find that their "inner" lock is already acquired.
This is due to the fact that you synchronized statements are anti-symetrical : for one thread, the outer synchronized lock is the inner one for the other thread and the other way around.
It's possible that one of the threads will enter both synchronized sections, blocking the other thread entirely until it's finished.
You need to simulate 'unfortunate timing'. Try adding sleep between two locks:
synchronized(fromAccount){
Thread.sleep(2000);
synchronized(toAccount){
Sleeps as suggested by Jon above can introduce non-determinism, you could make it deterministic using some coordinator like a latch instead. To clarify though, I'm thinking of it as a testing problem: how to prove a deadlock every time and that may not be what you're looking for.
See this code for an example and a blog post describing it a little.
The reason of deadlock is that thread A is wait for Thread B to release some resource before A continue; the same to thread B, it wont continue until thread A releases some resource. In other words, A and B wait forever to each other.
In the code snippet, synchronized can block other threads for while because only one thread can execute the block at the moment. thread.sleep() suspend the thread for 500 millisecond, then continue. The wait forever mutually condition doesnt satisfy, that why it is not deadlock.
Following snippet is a good example to illustrate deadlock
public class threadTest{
public class thread1 implements Runnable{
private Thread _th2;
private int _foo;
public thread1(Thread th2){};
public void run(){
for(int i = 0; i<100; i++){foo += foo;};
synchronized(this){this.notify()};
synchronized(_th2){
_th2.wait();
_foo += _th2.foo;
System.out.print(" final result " + _foo);
}
}
}
public class thread2 implements Runnable{
private final thread1 _th1; private int _foo;
public thread2(thread1 th1){};
public void Run(){
synchronized(_th1){_th1.wait()};
synchronized(this){
_foo += th1._foo();
this.notify();
}
}
}
}
}
//just ignore the way to access private variable in the class
Because there is no mechanism assuring the execution order of two threads, it is very possible thread 2 wont receive the notification from thread1 since it starts lately, thus it waits for the notification before continue execution. Same to thread1, it cant do next execution until it receives notification from thread2. both of them wait for each other forever, typical deadlock.

Categories