Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization Issue

 
Aron Daburn
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Marshal
Pie
Posts: 20902
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.

Henry
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic