[concurrency-interest] How to order the external calls?
Gregg Wonderly
gregg at cytetech.com
Wed Nov 17 10:24:50 EST 2010
On 11/17/2010 8:32 AM, nader at aeinehchi.com wrote:
> Suppose you have two methods initialize and terminate. Both methods call
> some external code that results in some state transition in the external
> component.
>
> Now, I want to ensure that terminate is not called while initialize is
> running, and vice versa. How can it be achieved effectively.
The ultimate answer depends on a number of factors. If there is no other use of
"synchronized" on methods in the class, you could simply put "synchronized" on
the method declaration.
If, on the other hand, there is already unrelated use of 'synchronized' on
methods, or synchronized(X) where X is the class name, then you can simply
create another "object" to synchronize on. What I typically do is.
Object singleUseLock = new Object();
public void method1() {
synchronized( singleUseLock ) {
unlockedMethod1();
}
}
public void method2() {
synchronized( singleUseLock ) {
unlockedMethod2();
}
}
private void unlockedMethod1() {}
private void unlockedMethod2() {}
But, if you don't want threads to block if someone is already calling one of the
other methods, then it gets more complicated and you need to put in the use of a
Lock object and call tryLock() and return when it is appropriate to skip the
call. In that case, you might use a boolean return value to say that you did,
or did not take the appropriate actions. Doing this kind of thing can make an
application more fragile from the perspective that you don't always take the
actions requested.
But, if your application has some pretty explicit control of logic using state
based transitions or other similar techniques then you can do this kind of thing.
Gregg Wonderly
More information about the Concurrency-interest
mailing list