Java – stop long running threads accessing the database
I started a few threads, but I didn't have a reference signal, a stop signal or something
I am using a ThreadGroup and always have its reference So I can do such a thing It seems impossible
Thread[] threads = new Thread[threadGroup.activeCount()]; int count = threadGroup.enumerate(threads); for(int i = 0; i < count; i++){ threads[i].interrupt(); }
This is an example of my thread
public void run{ try{ //myDAO.getRecords(); //this takes 30seconds to 60 //returns about 3 millions of records }catch(Exception e){ //log } }
When this thread is executing, I want to stop it in the middle Anyway, the database query is running, but I want to stop getting results
I still get results, even if I call interrupt () Is there any other way to do it? Finally, the task is to cancel the long - running SQL query from Java
Solution
There is no effect on thread call interrupts waiting for query output, because most JDBC drivers are immune to state It will remain blocked and the query will continue
Calling cancel causes the connection and thread to execute the query in the database For a while, it was ok, but it also killed the connection This can cause serious problems and soon become a bottleneck
An alternative but working solution is to get the ID of the thread executing the procedure / query (on the database side) and call:
KILL QUERY id;
To know the ID, in the right process, take the first line as: select connection_ ID();. This ID can be used to terminate it