[concurrency-interest] How to order the external calls?

nader at aeinehchi.com nader at aeinehchi.com
Wed Nov 17 11:38:26 EST 2010


Thanks Gregg for a comprehensive response.

For instance, I have a Module Manager with a certain life-cycle
(initialize, ... and terminate).  Each method (e.g. initialize) calls a
set of Modules, e.g.

// Based on the state, initialize and terminate are called
private State state;

void initialize(){
   foreach (module in modules){
      module.doSomething;
   }
}
void terminate(){
   foreach (module in modules){
      module.doSomethingElse;
   }
}

Now, I do not have control over the modules as a module may or may not
make external calls,e.g. a JMS server.  I do not have (and do not want)
control the locking mecahnism that each module has.

1. The "synchronized" locking mechanism that you mention here may
potentially lead to dead-locks?
2. Perhaps a ReentrantLock with some time-out would be a better solution?
3. Is there any better alternative than 1. & 2. ?

thanks.

> 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