Question: I'm interested to know the best practice for killing a long standing operation that is running as a background thread (lets call this thread WorkerThread
) in Java 1.2.
Scenario
Specifically, I'm developing an application for Blackberry devices whereby I make a HTTP connection. Big picture: a URL request if forwarded to a background thread (WorkerThread
), the thread makes the request and returns the result using a call back.
Scenario Details
Now there exists a situation where at connection time, a data connection exists but then for whatever reason (drives through a tunnel) that connection no longer exists. Due to a limitation in Blackberry's design architecture, that actual connection will hang as the time out is fixed to be 2 minutes. As a result, there's a crucial need to kill a connection that has been hanging for a relatively (15 seconds) long period of time.
My Current Solution - 2 Theads?
Right now my current solution is to run WorkerThread
inside another thread (lets call this new thread MonitorThead
). MonitorThread
starts WorkerThread
, sleeps for 1000ms and then routinely checks if WorkerThread
is still alive. If after 15 seconds WorkerThread is still alive, MonitorThread puts WorkerThread to sleep and exits. Is this really the best possible approach?
Summary of Question & Key points
In summary, below is the core question and key restraints associated with the question. Cheers!
How do I successful kill a java background thread that is stuck in a specific operation?
Scenario Restraints:
- No control of having operation pause and check the threads requested state
- Specific to Blackberry's implementation of Java ME 1.2 and its Thread API so no explicit kill() method
- Most concerned about the best practice and how to most safely kill a holding thread.
Follow Up/Edit
Neil Coffey recommended that I simply hold a reference to the connection object and instead call close() on that object. I am currently looking into this...