当私有实例变量超出作用域时,Java终止线程



我正在规划一个类,它动态地打开到数据库的连接来存储一些设置。如果在一段特定时间内未使用,或者调用方法结束,类应该自动关闭连接。

这是我到目前为止的解决方案,只显示了相关的部分:

public class DBSettings {
    // ...
    private int ConnectionTimeout = 5000; 
    private ExecutorService Executor;
    private long LastTimeUsed;  
    // ...
    public DBSettings(DBConnection Conn) {
        Connection = new DBConnection(); // class handles Connection to Database
        // ...
    }
    private void connect() {
        try {
            if (!Connection.isOpen()) {
                Connection.openConnection(DBUrl, DBUserName, DBPassword);
                LastTimeUsed = System.currentTimeMillis();
                Executor = Executors.newSingleThreadExecutor();
                Runnable closeRunnable = new Runnable() {
                    @Override
                    public void run() { 
                        while (System.currentTimeMillis() < (LastTimeUsed + ConnectionTimeout)) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) { }
                        }
                        disconnect(); 
                    }
                };
                Executor.submit(closeRunnable);
            }
        } catch (Exception e) { // ... }
    }
    private void disconnect() {
        if (Connection!=null) {
            if (Executor!=null) {
                Executor.shutdown();
            }
            Connection.closeConnection();
        }
    }
    public void setValue(String group, String key, String value) {
        // ...
        LastTimeUsed = System.currentTimeMillis();
    }
}

ExecutorService在5秒后停止,连接关闭。但不幸的是,如果调用者方法结束,它将至少运行5秒。

我的测试程序:
private static void testDBSettings(DBConnection Conn) {
    // using my class
    DBSettings settings = new DBSettings(Conn);
    // set first value, open connection
    settings.setValue("Groupname", "Keyname", "Value");  
    Thread.sleep(1000);
    // set second value, extend connection lifetime
    settings.setValue("otherGroupname", "otherKeyname", "otherValue");  
    Thread.sleep(1000);
    // here is the problem: after "settings" goes out of scope my class should 
    // stop or terminate the ExecutorService without the need to call an extra method.
}

我读了很多关于线程的书,但是找不到解决方法。

尝试使用ScheduledExecutorService的另一种方法-结果相同。

finalize()不起作用,因为它只被垃圾回收调用。

有人能帮我吗?

在java中没有办法跟踪这个。

最接近的是使用try-with-resource

try(MyClass myClass = new MyClass()){
    myClass.doSomething();
} // Here myClass.close(); will be called.

最新更新