How can I destroy such a thread that perform very long operation?
I need to solve this problem without setting timeouts for SQL query. I know that Thread.destroy() is deprecated.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Sample {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/db");
conn.createStatement().execute("SELECT * FROM some_table");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
Jon is right, setting timeouts is the correct way to resolve the problem.
However, you could have another thread in the background running as a timer which holds a reference to the thread and fires an interrupt. This is effectively a home-grown timeout though!