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 Clarification required on synchronized block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Clarification required on synchronized block" Watch "Clarification required on synchronized block" New topic

Clarification required on synchronized block

shan raj
Ranch Hand

Joined: Dec 16, 2008
Posts: 42
I have two list a, b. One thread is adding the data into the list and start the timer if the timer is not already started.

Another thread is a timer Task thread that will wake up for every 5 secs to read the list and process as follows.

Could any clarify my questions in the comments of the code. if my logic is wrong please provide the better way to implement to avoid synchronization issue.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 443

The answer to 1 is yes but I think you have more problems than that.

I'd simplify this down to synchronisation that covered A & B for reads and writes, with a single object to signal between threads and then optimise it later if you have to, you seem to be struggling a bit. If your not 100% confident simple is always best.

"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
You must synchronize on both lists before looking at their combined
size. Otherwise, one of the add() methods could loose an object while
MyTask thinks the lists are empty. To process the non-empty lists, you
can synchronize separately again if you wish.
Jim ... ...

shan raj
Ranch Hand

Joined: Dec 16, 2008
Posts: 42
Thanks for your suggestions.

Chris Hurst ,

Could you provide sample program or tutorial to use the single object to signal between the thread.

I will also try "Jim Hoglund" suggestion given in the previous posts.

I agree. Here's the link:
subject: Clarification required on synchronized block
It's not a secret anymore!