What is the best possible way to ensure a minimum time gap between 2 asynchronous method calls. For e.g. if I have 2 methods methodA() and methodB() and there are called asynchronously, how can I ensure that there is a minimum time gap between the calls i.e. the 2nd call must block till that time gap has expired and then only proceed. I have a few solutions in my head but I am looking for a good one.
As Paul Sturrock said use boolean varialbe as flag
Joined: Jan 01, 2007
Paul Sturrock wrote:Describe what you mean be "when needed". Wrapping the call in some conditional logic is easy.
Let's say there are 2 methods m1() and m2().
The time spacing between m1() and m2() must never be less that say T
So let say m1() was called at some time instant t1.
And then m2() is called at some time instant t2.
Now if t2-t1 < T then block for time t2-t1 and then proceed with m2()
if t2-t1 >= T then proceed with m2()
Also one thing to note is that calls to m1() and m2() are always made in pairs and there could be several such pairs happening simultaneously.
Perhaps use a Semaphore, initially with no permissions. m2()'s first job is to take a permission from the Semaphore (and therefore waits till it is ready). m1()'s first job is to start a TimerTask delayed for time T, which gives a permission back to the Semaphore.
Steve Luke wrote:Perhaps use a Semaphore, initially with no permissions. m2()'s first job is to take a permission from the Semaphore (and therefore waits till it is ready). m1()'s first job is to start a TimerTask delayed for time T, which gives a permission back to the Semaphore.
Yeah, I think the Semaphore is a bit better than Lock in this case. For Lock/Condition m2() must be waiting before the timeout occurs. If not, then the timeout can signal the Condition before m2() awaits it and the signal could be lost making m2() wait forever. There are workarounds of course, but the Semaphore is nice and easy. If the timeout occurs before m2() gets to acquire(), then acquire() returns immediately.