My goal is to listen to changes in 2 or more tables in a database. So I implemented one thread per table. In this case to handle the threads I have used Executor Service.
I need to stop these running threads as per the request of the client side. Here is the current implementation.
public class TableListener extends Thread {
private String prevName;
private final String query;
public TableListener(String query) {
this.query = query;
}
public void run() {
while (true) {
try {
Thread.sleep(Integer.parseInt(Settings.REFRESH.trim()));
} catch (InterruptedException e) {
e.printStackTrace();
}
CommonDao commonDao = new CommonDao();
String name = commonDao.loadTable(this.query);
if(prevName != null && !prevName.equalsIgnoreCase(name)) {
System.out.println("prevName: " + prevName + "name: " + name);
} else {
System.out.println("no changes");
}
prevName = name;
}
}
}
public class TableListenerService{
public static ExecutorService pool;
public void initializeThreads() {
pool = Executors.newFixedThreadPool(2);
pool.execute(new TableListner("select * from person"));
pool.execute(new TableListner("select * from demo"));
}
public void stop() {
pool.submit(new Runnable() {
public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
System.out.println("Interrupted, so exiting.");
}
}
});
try {
if (pool.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("task completed");
} else {
System.out.println("Forcing shutdown...");
pool.shutdownNow();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
But when executing the stop method, it gets below error
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.demo.service.TableListner.run(TableListner.java:19)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.demo.service.TableListner.run(TableListner.java:19)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
could anyone support me in overcoming this and any optimized solution for this problem?