Java - 停止访问数据库的长时间运行的线程 [英] Java - Stop a long running thread which accesses database

查看:171
本文介绍了Java - 停止访问数据库的长时间运行的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我启动了几个线程,但是我没有通过信号或其他东西来阻止它们的引用。
例如,我不能将像 running = false 这样的变量传递给那些线程,因为我没有他们的引用,但是有他们的名字。

I start couple of threads, but I do not have their references to stop by signalling or something. For example, I can't pass a variable like running=false to those threads, because I do not have their references, but have their names.

我正在使用 ThreadGroup ,我总是引用它。所以我可以这样做。似乎它不起作用。

I'm using a ThreadGroup and always I have the reference of it. So I can do something like this. Seems to be it doesn't work.

    Thread[] threads = new Thread[threadGroup.activeCount()];
    int count = threadGroup.enumerate(threads);
    for(int i = 0; i < count; i++){
        threads[i].interrupt();
    }

这是我的主题的一个示例。

This is a sample of my thread.

    public void run{

         try{
             //myDAO.getRecords();
             //this takes 30seconds to 60
             //returns about 3 millions of records

         }catch(Exception e){
             //log
         }
    }

当这个线程正在执行时,我想在中间停止它。
无论如何batabase查询正在运行,但我想停止获得结果。

When this thread is executing, I want to stop it in the middle. Anyway batabase query is running, but I want to stop getting results.

即使我调用中断,我仍然得到结果( )
有没有其他方法可以做到这一点还是我做错了什么?最终任务是从Java中取消长时间运行的SQL查询。

Still I'm getting results even I call interrupt(). Are there any other ways to do this OR have I done anything wrong ? Ultimately the task is to cancel a long running sql query from Java.

推荐答案

调用中断对于一个等待查询输出的线程没有影响,因为大多数JDBC驱动程序都不受状态影响。它仍然会被阻止,查询将继续执行。

Calling interrupt for a thread that is say waiting for the query output has no affect as most of the JDBC drivers are immune to the status. It will still remain blocked and the query will keep executing.

调用取消将终止连接并执行线程数据库中的查询。偶尔它可以,但它也会杀死连接。这可能会产生严重的问题,很快就会成为瓶颈。

Calling cancel will kill the connection and the thread executing the query in the database. For once in a while it is ok but it also kills the connection. This can create serious problems and will soon turn out to be the bottleneck.

另一种可行的解决办法是获得 ID 执行过程/查询的线程(在数据库端)并调用:

An alternative but a working solution would be to get the the ID of the thread executing the procedure/query (on the database side) and to call:

KILL QUERY id;




KILL QUERY终止连接当前正在执行的语句,但是离开连接本身完好。

KILL QUERY terminates the statement that the connection is currently executing, but leaves the connection itself intact.

要知道ID,请在程序中将第一行作为: SELECT CONNECTION_ID(); 。此ID可用于终止它。

To know the ID, right In the procedure, have the first line as: SELECT CONNECTION_ID();. This Id can be used to terminate it.

这篇关于Java - 停止访问数据库的长时间运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆