The best way I found was to create another class to detect when the connection was lost.
This class would create 2 threads, one that calls a method to check if the database exists and then set a flag to true; and another that would check if the flag was true after a certain amount of time. If it was still false after the certain amount of time, it means that the database connection was lost and the first thread is locked waiting for the timeout. This way I don't need to wait for the timeout to happen to detect it.