wood burning stoves
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threads Basics" Watch "Threads Basics" New topic

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 {
} 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
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.
I agree. Here's the link: http://aspose.com/file-tools
subject: Threads Basics
jQuery in Action, 3rd edition