Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads Basics

 
Rishi Kanth
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi , this maybe a silly doubt but i want to make myself clear.

We use the keyword Synchronized to avoid the race condition. when a thread wants to execute a Synchronized method, firt it needs to grab the lock to the object. If any other thread comes up it needs to wait.
My doubt is wht is this lock ??? actually. Example in the class shown:

public class BusyFlag {
protected Thread busyflag = null;
public Synchronized void getBusyFlag () {
while (busyflag != Thread.currentThread()) {
if (busyflag == null)
busyflag = Thread.currentThread();
try {
Thread.sleep(100);
} catch (Exception e) {}
}
}
public Synchronized void freeBusyFlag () {
if (busyflag == Thread.currentThread()) {
busyflag = null;
}
}
}

Grabing a lock to the object means obtaining the lock of the class object or...??
Can you explain me with some other explain.
I hope your understanding me guys.

Thank You
Rishi
 
Purushoth Thambu
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assume that every class you create when compiled will have an private mutex/lock object within the class (for simplicity let's assume it's boolean). You cannot create this lock object it's done by JVM behind the scene. When first thread access the synchronized method the JVM check the boolean value ,turns it on to true and continue executing the synchronized methods. The second thread also tries to call a synchronized method on the same object. The JVM again check the boolean value since it's true (meaning it's been locked) this thread blocks and waits for the lock to be available.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic