Joe Nellis <newsgroups <at> jnellis.net> writes:

> 
> Hi Guillermo,
> 
> The wait loop idiom:
> 
> synchronized(obj){
>   while( condition does not hold ){
>     obj.wait();
>     // do stuff we were waiting for
> }
> 
> Without the loop, your threads wait automatically and depend on obj.notify
> getting called from some control thread, which I think is never happening or
> is happening before these threads actually get to the wait statement, or a
> control thread is never releasing the lock, many other possibilities that
> without seeing the code it's quite pointless to speculate further.
> 
> In any case, I would take a different approach and use the concurrency
> package and perhaps the Executors.newCachedThreadPool or newFixedThreadPool
> factories. Basically, start one of these up, wrap the third party lib work
> in a Runnable or Callable annonymous inner class then submit it to the
> executor.  The executor returns a Future object that you can perform a timed
> blocking wait on it for it to finish it's work, if it doesn't finish in some
> timeframe it throws an exception (but the task is free to finish) and you
> should maybe send a 202 Accepted return code.
> 
> public void handleGet(){
>     // perhaps start this pool in the application createRoot
>     // and add it to the context attributes map.
>     // you must call execution.shutdown() when the
>     // component is stopped.
>     ExecutorService executor =
>         getContext().getAttributes().get("3rdPartyThreadPool");
>     final Request req = getRequest();
>     Future<Foo> pendingResult =
>         executor.submit( new Callable<Foo>(){
>           public Foo call(){
>             Foo result = null;
>             // do 3rd party lib work here, use req variable.
>             return result;
>           }
>     });
>     try{
>       Foo theResult = pendingResult.get(waitTime, timeunit);
>       // getResponse().setEntity(theResult);
>     }catch (TimeoutException ex){
>        // what is plan B?  return 202
>     }
> }
> 


Hi,

This is actually very similar to what I'm doing.
I'm using an ExecutorSesvice thread pool manager, and then I submit a Runnable 
task from the handleGet in the Resource.
What I was originally trying to do was to do a wait() on the thread that 
submitted the task, and then have the runnable task do a notify() when it 
finished. 

It was working from the beginning, but I was testing it wrong :P

I now changed that to using the Future to wait instead, as the solution is 
cleaner and I can specify a timeout.

We'll go with that for now, but if there are timeout problems, we might need to 
change to using a resource ticket. I think that approach would also work if 
everything was handled by a single thread.

Thanks for your responses!




Reply via email to