如何强制超时DriverManager.getConnection()方法调用? [英] How to force timeout for DriverManager.getConnection() method call?

查看:390
本文介绍了如何强制超时DriverManager.getConnection()方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序将建立与MySQL连接并执行查询。有时, DriverManager.getConnection()方法调用需要2秒,有时需要30秒。是否有任何方法可以控制此方法在2秒后超时?

I have an application which will establish DB connection with MySQL and execute queries. Sometimes the DriverManager.getConnection() method call takes 2 seconds and sometimes it takes 30 seconds. Is there any way to control this method to timeout after 2 seconds?

DriverManager.setLoginTimeout()似乎工作。

其实,我可以设置超时 statement.executeQuery()我的超时值,并在唤醒后关闭连接。但它的连接建立部分,我不能真正设置超时。

Actually, am able to set timeout for statement.executeQuery() by sleeping the thread for my timeout value and closing the connection after wakeup. But its the connection establishment part where I couldn't really set the timeout.

感谢任何帮助。

推荐答案

如果没有其他选项,你可以在一个单独的线程中执行调用,如果它在2秒内没有完成,你会放弃/忽略。

If there's no other options, you could always just execute the call in a separate thread, which you abort/ignore if it doesn't finish in 2 secs.

EDIT
下面是一个我正在想的例子:

EDIT Here's an example of what I was thinking:

public class Dummy extends Thread {
private volatile Connection conn = null;
@Override
public void run() {
    try {
        this.conn = DriverManager.getConnection("foobar") ;
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
static public Connection getConnection() {
    Dummy d = new Dummy() ;
    d.start() ;
    try {
        Thread.sleep(2000) ;
    } catch (InterruptedException e) {}
    return d.conn ;
}
}

然后你可以调用静态Dummy.getConnection )方法中的其他地方的代码。一个缺点是这个方法总是需要2秒,但是当线程完成时立即返回,不会太难。

Then you can just call the static Dummy.getConnection() method other places in your code. One drawback is that this method will always take 2 secs, but changing it to return immediately when the thread is finished isn't too hard.

这篇关于如何强制超时DriverManager.getConnection()方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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