[concurrency-interest] Cancellation convention

Brian Goetz brian at quiotix.com
Tue Jun 6 16:16:48 EDT 2006

> Is it the convention to use Thread.interrupt() to do cancellation of a 
> task in another thread?  Presumably the Thread being run must either be 
> calling API code that is interruptible or check itself for the 
> interrupted state regularly.

Interrupting a thread when you do not know (a) exactly what code is 
running in it and (b) how it will react to interruption is ill-advised. 
  Better to use the cancel() feature of Future (to avoid problem (a)) 
and code your tasks to deal properly with IE (to avoid (b)).

You can then run such tasks in a standard thread pool, which is usually 
preferable to forking off a separate thread.

(This material is covered fairly extensively in Ch7 of JCiP.)

> Specifically I'm interested in being able to cancel long running JDBC 
> calls (using PreparedStatement.cancel()).  Would a sensible way be to 
> fork off the PreparedStatement execution in another thread and have the 
> main thread wait for the second thread to complete, but if it is 
> interrupted then call the PreparedStatement.cancel() and throw an 
> exception out to indicate the cancellation succeeded?  Just after some 
> best practice advice.

More information about the Concurrency-interest mailing list