title: How to isolate your program from calls to a "bad" API?
body: <p>When I developed a piece of (academic) software using Java, I was forced to use an API that was rather badly implemented. This means that calls to this API for a certain set of input data would sometimes never return. This must have been a bug in the software as the algorithms that it offered were deterministic ones, and sometimes it would terminate on a set of data, sometimes it would run into an infinite loop on the same set of data...</p>
  
  <p>However, fixing the API or reimplementing it was simply beyond scope. I even had the source but the API heavily relied on other APIs which were undocumented and without source and had by the time vanished from the web (or never been there?). On the other hand, this "bad" API was the only one out there that solved the specific problem I had, so I really had to stick with it.</p>
  
  <p>The question is: what is the cleanest way of dealing with an API that behaves that, well, nasty? When I faced this problem I decided to put the calls to the API into a separate thread. Another thread would then occasionally check if this thread had terminated. If a certain amount of time had passed, I would kill the processing thread using <code>Thread#stop()</code> and start the processing again, hoping that it would return the next time. Now, I know (and knew back then) that this method is deprecated and must not be used. But in this academic context it was acceptable to have the software <em>potentially</em> run into an undefined state instead of having it crash. </p>
  
  <p>It was also not acceptable to just ignore the processing thread that had run into an infinite loop because it did some quite CPU-intensive operations that would slow down the user's machine significantly.</p>
  
  <p>Another way which I didn't try is to start the processing in a separate <em>process</em> instead of a thread, because a sub-process can be killed cleanly without putting the software in an inconsistent state. Or could the new <code>SwingWorker</code> class (which wasn't yet available) have done the job? It has a <code>cancel()</code> method, but the docs say that it <em>"Attempts to cancel execution of this task"</em>, so it doesn't look like a reliable approach either.</p>