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...
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.
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 Thread#stop()
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 potentially run into an undefined state instead of having it crash.
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.
Another way which I didn't try is to start the processing in a separate process instead of a thread, because a sub-process can be killed cleanly without putting the software in an inconsistent state. Or could the new SwingWorker
class (which wasn't yet available) have done the job? It has a cancel()
method, but the docs say that it "Attempts to cancel execution of this task", so it doesn't look like a reliable approach either.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…