In a swing application, I would like to re-utilize a spawned thread instead of creating a new one to serve requests. This is because the requests would be coming in short intervals of time and the cost of creating a new thread for every request could be high.
I am thinking of using the interrupt() and sleep() methods to do this as below and would like to know any potential performance problems with the code:
public class MyUtils {
private static TabSwitcherThread tabSwitcherThread = null;
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
tabSwitcherThread = new TabSwitcherThread();
tabSwitcherThread.start();
}
else
tabSwitcherThread.interrupt();
}
private static class TabSwitcherThread extends Thread{
@Override
public void run() {
try {
//Serve request code
//Processing complete, sleep till next request is received (will be interrupted)
Thread.sleep(60000);
} catch (InterruptedException e) {
//Interrupted execute request
run();
}
//No request received till sleep completed so let the thread die
}
}
}
Thanks
I wouldn't use sleep()
and interrupt()
- I'd use wait()
and notify()
if I absolutely had to.
However, is there any real need to do this instead of using a ThreadPoolExecutor
which can handle the thread reuse for you? Or perhaps use a BlockingQueue
in a producer/consumer fashion?
Java already provides enough higher-level building blocks for this that you shouldn't need to go down to this level yourself.
I think what you're looking for is a ThreadPool. Java 5 and above comes with ThreadPoolExecutor. I would suggest you use what is provided with Java instead of writing your own, so you can save yourself a lot of time and hairs.
Of course, if you absolutely has to do it the way you described (hey, sometimes business requirement make our life hard), then use wait() and notify() as Jon suggested. I would not use sleep() in this case because you have to specified timeout, and you never know when the next request will come in. Having a thread that keep waking up then go back to sleep seems a bit wasteful of CPU cycle for me.
Here is a nice tutorial about the ThreadPoolExecutor.
EDIT:
Here is some code example:
public class MyUtils {
private static UIUpdater worker = null;
private static ExecutorService exeSrv = Executors.newFixedThreadPool(1);
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
worker = new UIUpdater();
}
//this call does not block
exeSrv.submit(worker, new Object());
}
private static class UIUpdater implements Runnable{
@Override
public void run() {
//do server request and update ui.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With