File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes How to: convert Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to: convert "guarded block" into "lock objects"?" Watch "How to: convert "guarded block" into "lock objects"?" New topic

How to: convert "guarded block" into "lock objects"?

Aji Prasetyo
Ranch Hand

Joined: Jun 13, 2007
Posts: 65
Dear guys,

Below is the progam I've been writing. It has two threads, one (PanelView) is for displaying the data in the file, and one (DataCreator) is for writing the data into the file. In the middle there is an object to synchronize the two threads. The object has two methods, to read and to write data. To synchronize, right now I uses "guarded block" to toggle between reading and writing the data.

My question is how to convert this "guarded block" style of synchronizing into "lock object" style? I means, "the Lock.trylock() and Lock.unlock()" style of synchronizing. I've tried to convert it myself, but noluck so far. I am sorry if my phrase is unclear or confusing, but I studied threading mostly from sun's java tutorial.

Why I need to convert my synchronizing object? Well, firstly I want to study like the rest of the folks here. Secondly, I think that by using "lock object" the synchronizing method will be more effective since the method doesn't wait(). Furthermore, the code line can be reduced.

Thank you for your attention.

And this is the code:

sarvesh meens
Ranch Hand

Joined: Mar 31, 2006
Posts: 43

So,synchronizing each class is the pargmatic solution.

Am still curious about the tool.
Is there any tool which high-lights blocks where threads interleave,given the code?
Aji Prasetyo
Ranch Hand

Joined: Jun 13, 2007
Posts: 65
I am sorry, but I am not quite sure what you mean.
blocks where threads interleave

But if you're asking about where the threads interleaves, then it is in the ScanDataPool class.

The readData and writeData method is both synchronized method. The mehod will wait according to the boolean variable refreshed. Please note that you have to toggle the boolean variable and at the end of the method you have to call notifyAll to tell the waiting method to go on.

I am sorry if my explanation is inadequate.
I agree. Here's the link:
subject: How to: convert "guarded block" into "lock objects"?
It's not a secret anymore!