You can set a timeout on executing a query. SQLException
will be thrown if the query doesn't complete in time and times out:
preparedstatement.setQueryTimeout(seconds);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ){
// do some stuff
}
Have a look at setQueryTimeout
documentation