File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Threads Basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threads Basics" Watch "Threads Basics" New topic
Author

Threads Basics

Rishi Kanth
Ranch Hand

Joined: May 23, 2006
Posts: 43
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

Joined: May 24, 2003
Posts: 425
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.
 
wood burning stoves
 
subject: Threads Basics