wood burning stoves
The moose likes Threads and Synchronization and the fly likes Synchronization Issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Synchronization Issue" Watch "Synchronization Issue" New topic

Synchronization Issue

Aron Daburn
Ranch Hand

Joined: Mar 18, 2007
Posts: 36
Here's a riddle for you all.

The Setup:
I have function A and function B. I want function A and B to be synchronized within object O. Multiple threads will be accessing object O. When function B is running, no function As will be running and vice-versa.

The Problem:
Function A should not stop another function A from running. Simply having a lock for A and B will cause one A to lock out another A. How do you synchronize A and B together without locking multiple threads on A?
Henry Wong

Joined: Sep 28, 2004
Posts: 20374

Do you only want this functionality with A? And not B?

If so, you can use a reader writer lock -- java.util.concurrent.locks.ReentrantReadWriteLock. Have method A grab the reader lock, and have method B grab the writer lock.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
I want function A and B to be synchronized within object O...

If functions A and B are guaranteed to run at different times,
controlled by other factors, apparently, why do you want them
to be synchronized?
Jim ...

Aron Daburn
Ranch Hand

Joined: Mar 18, 2007
Posts: 36
Henry, a read/write lock seems to be exactly what I am looking for, thanks!

I have an object O that establishes a connection with a server and requests are rean through that object. To not have each thread have performance hit of initializing a connection, I am caching that object and having each thread simply call the get request (object O is thread safe to handle simultaneous get requests). My code needs to reinitialize the connection after X get requests which means when one thread is reinitializing the connection, no get requests should proceed. So, I think a read/write lock will be perfect for this.
It is sorta covered in the JavaRanch Style Guide.
subject: Synchronization Issue
It's not a secret anymore!