File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes using yield in implementing locking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "using yield in implementing locking" Watch "using yield in implementing locking" New topic

using yield in implementing locking

Sam Davidson

Joined: Sep 22, 2002
Posts: 1
I have come up with a solution for locking that appears to be quite simple.
The remote client checks the Hashtable if the record is already locked or not. If it sees a lock exists on it the client calls Thread.yield() to yield the CPU.
Now any other client is free to try to lock the record it wants to.
The thread scheduler will after random time allow the yielded thread to continue its operation and if the lock is nto there anymore it will be able to lock the record.
This approach works but it seems very simple compared to the wait/notify approach taken by java ranchers here.
What are the drawbacks of my approach?
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

What are the drawbacks of my approach?

You are likely to waste a lot of CPU cycles by repeatedly checking if the record is locked and calling yield(). It makes much more sense to try to lock the record only after being notified that it has been unlocked. In addition, the call to yield() is just a suggestion, -- the thread scheduler may decide to continue to run the thread that just yielded, hogging the CPU.
[ September 29, 2002: Message edited by: Eugene Kononov ]
Max Habibi
town drunk
( and author)

Joined: Jun 27, 2002
Posts: 4118
Originally posted by Sam Davidson:
What are the drawbacks of my approach?

Hi Sam,
I like your approach, and it's very similiar to the one advocated by my book. However, I would suggest that you not use yield(), as it's behaviour is platform dependent. Try wait instead.
M, author
The Sun Certified Java Developer Exam with J2SE 1.4

Java Regular Expressions
I agree. Here's the link:
subject: using yield in implementing locking
It's not a secret anymore!