• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization understanding

 
sandipan chakrabarti
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.concurrent.atomic.AtomicBoolean;
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
try {
System.out.println("11111111");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void decrement() {
c--;
}

public synchronized int value() {
return c;
}
}

public class test2 extends Thread{
static SynchronizedCounter c = new SynchronizedCounter(); ;
public void run(){
c.increment();
}
public static void main(String[] args) {
test2 t = new test2();
test2 t1 = new test2();
t.start();
t1.start();
}
}

The result-----

11111111
11111111

Q if the SynchronizedCounter methods are synchronized then I can assume that when one thread enters the critical section in increment() then the other thread is blocked. then why 11111 is printed twice instead of once??
 
Henry Wong
author
Marshal
Pie
Posts: 21024
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q if the SynchronizedCounter methods are synchronized then I can assume that when one thread enters the critical section in increment() then the other thread is blocked. then why 11111 is printed twice instead of once?


The other thread *is* blocked -- because it is waiting to acquire the lock. However, once the wait() method is called, it will release the lock, allowing the other thread to acquire the lock.


Henry
 
amitt jainn
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am totally agreed with Henry..
explaning it further syncing with the question.



actually when we call wait() on an object, it relinqushes the monitor it holds and goes to the waiting thread pool of that object ('this' in this case). Now this thread will not gain its ready state until a notify is called on this object (this in our example).

Now since the thread has already released the monitor another thread can very smoothly obtain monitor on this object.

That is why your program returned

11111111
11111111

Regards
Amit
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy sandipan chakrabarti ,

Kindly make use of the Code Tags when posting the java code
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic