• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why two threads accessing synchronized method at the same time

 
Parmeet Singh
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a below given programme, when i run executer class, it makes two NoWai threads and these thread gets the reference of Workspace class.
Workspace class has a synchronized method name doDa(),

My question: why and how two threads are able to access synchronized method doDa() at the same time.

We can confirm this by checking the output i.e.

Message: WorkPlace@923e30 first
Thread name: Thread-1

Message: WorkPlace@923e30 first
Thread name: Thread-0

Message: WorkPlace@923e30 second
Thread name: Thread-1

Message: WorkPlace@923e30 second
Thread name: Thread-0

it shows two threads enter the synchronized method at teh same time.


class NoWai extends Thread{
public NoWai(){
start();
}

public void run(){
WorkPlace.getInstance().doDa();
}
}

class WorkPlace{
private Object lock = new Object();
private WorkPlace(){
}

static WorkPlace work = null;

public static WorkPlace getInstance(){
if(work == null){
work = new WorkPlace();
}
return work;
}


public synchronized void doDa(){
TUtil.print(this.getInstance() + " first");

TUtil.print(this.getInstance() + " second");
}
}


class Executer {
public static void main(String[] args) throws Exception{
for(int i =0 ; i < 2; i++){
new NoWai();
}
}
}

class TUtil{
static void print(String message){
System.out.println("Message: "+message +
"\nThread name: "+Thread.currentThread().getName() + "\n");
}
}
 
Henry Wong
author
Sheriff
Posts: 22531
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like you may have a race condition in your first/second call to the getInstance() method -- possibly giving you two different objects.

To be able to tell if this is happening, remove the getInstance() call in the call to the print() method. This is not needed anyway, because the "this" object is that instance, and the extra call to getInstance() will just hide the race condition.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and synchronize the getInstance() method!
 
Parmeet Singh
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanking you ..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!