1+ package com .xforg .concurrency ;//: concurrency/InterruptingIdiom.java
2+ // General idiom for interrupting a task.
3+ // {Args: 1100}
4+ import java .util .concurrent .*;
5+
6+ class NeedsCleanup {
7+ private final int id ;
8+ public NeedsCleanup (int ident ) {
9+ id = ident ;
10+ System .out .println ("NeedsCleanup " + id );
11+ }
12+ public void cleanup () {
13+ System .out .println ("Cleaning up " + id );
14+ }
15+ }
16+
17+ class Blocked3 implements Runnable {
18+ private volatile double d = 0.0 ;
19+ public void run () {
20+ try {
21+ while (!Thread .interrupted ()) {
22+ // point1
23+ NeedsCleanup n1 = new NeedsCleanup (1 );
24+ // Start try-finally immediately after definition
25+ // of n1, to guarantee proper cleanup of n1:
26+ try {
27+ System .out .println ("Sleeping" );
28+ TimeUnit .SECONDS .sleep (1 );
29+ // point2
30+ NeedsCleanup n2 = new NeedsCleanup (2 );
31+ // Guarantee proper cleanup of n2:
32+ try {
33+ System .out .println ("Calculating" );
34+ // A time-consuming, non-blocking operation:
35+ for (int i = 1 ; i < 2500000 ; i ++)
36+ d = d + (Math .PI + Math .E ) / d ;
37+ System .out .println ("Finished time-consuming operation" );
38+ } finally {
39+ n2 .cleanup ();
40+ }
41+ } finally {
42+ n1 .cleanup ();
43+ }
44+ }
45+ System .out .println ("Exiting via while() test" );
46+ } catch (InterruptedException e ) {
47+ System .out .println ("Exiting via InterruptedException" );
48+ }
49+ }
50+ }
51+
52+ public class InterruptingIdiom {
53+ public static void main (String [] args ) throws Exception {
54+ if (args .length != 1 ) {
55+ System .out .println ("usage: java InterruptingIdiom delay-in-mS" );
56+ System .exit (1 );
57+ }
58+ Thread t = new Thread (new Blocked3 ());
59+ t .start ();
60+ TimeUnit .MILLISECONDS .sleep (new Integer (args [0 ]));
61+ t .interrupt ();
62+ }
63+ }
0 commit comments