Listing 1:  Parallelism with Asynchronous Method Calls

asyncOne();
asyncTwo();
 
.
.
. // other asynchronous processes

while (/* some result still need */) {
                  // blocked, awaiting finish of some asynchronous process
                  int result = listen ();
                  if (result == RESPONSE_TYPE_1) {
                                    // do some processing
                  } else if (result == RESPONSE_TYPE_2) {
                                    // do some other processing
                  } else ... {
                                    // yet more asynchronous process handling
                  }
                  // but how do you cancel one of these processes?
}
 
 
Listing 2:  Lightweight Thread Wrapper

abstract class SyncToAsync extends Thread {

                  protected Object result;
 
                  public Object getResult() {
                                    return result;
                  }
 
                  // used to force cancellation of processing
                  public void cancel () {
                                    try {
                                                      this.join();
                                    } catch (InterruptedException ie) {
                                                      // ignore purposely
                                    }
                                    // perform some logical rollback
                  }
 
                  public boolean finished() {
                                    return (result != null);
                  }
}
 
 
Listing 3:  Pseudoparallelism with Wrapped Synchronous Method Calls

SyncToAsync asyncOne =
                  new SyncToAsync ()   {
                                    public void run() {
                                         // do some synchronous processing
                                            result = doSyncOne();
}
                  };
 
SyncToAsync asyncTwo =
                  new SyncToAsync()   {
                                    public void run() {
                                         // do some synchronous processing
                                            result = doSyncTwo();
}
                  };
 
asyncOne.start();
asyncTwo.start();
.
.
. // other asynchronous processes
 
while (/* some result still needed */) {
                  if (asyncOne.finished()) {
                   /* a particular result from asyncOne happens to
      short-circuit asyncTwo */
                  if (someTest(asyncOne.getResult())) {
                                    asyncTwo.cancel();
                                    break;
                  }
                  } else if (asyncTwo.finished()) {
                                    // do some other processing
                  } else ... {
                                    // yet more asynchronous process handling
                  }
}