Is it possible to cancel a JDBC connection?

Asked

Viewed 56 times

0

I’m using the following code in a Thread:

            try {
                Class.forName("org.postgresql.Driver");
                DriverManager.setLoginTimeout(60);
                conexao = DriverManager.getConnection(url,usuario,senha);
            }catch(Exception e){
                mensagemErro = e.getMessage();
            }

And in another Thread(GUI) has a window as cancel button, but I do not know how to cancel Drivermanager. connection is a public variable.

Show 1 more comment

1 answer

0

Specifically for the Postgresql Driver, according to changelog, at least from the version 9.3-1101 of 14/02/2014 you can call Thread.interrupt() on Thread trying to make the connection.

This is a technique known in Java to "wake up" threads that are waiting in some I/O. operation and it is at this point that the exception is InterruptedException (the one you need to treat each time you call the Thread.sleep) makes some sense.

Basically, the method of interrupt() activates a flag in the thread and unlocks it (if locked), then it has the change to treat the flag and stop processing.

According to the change log link, the Driver checks the interrupt bit and throws an exception. Then just ignore it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.