I need to read the data from a table every minute through thread & then perform certain action.
Should I just start a thread & put it in sleep mode for 1 minute, once the task is done. And then again check if the table has any data, perform the task again & go to sleep for 1 minute...
Is this the right approach? Can any one provide me some sample code in Java for doing the same?
Thanks!
When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.
Worker thread is a continuous parallel thread that runs and accepts messages until the time it is explicitly closed or terminated. Messages to a worker thread can be sent from the parent thread or its child worker threads. Through out this document, parent thread is referred as thread where a worker thread is spawned.
A Worker is an object which performs some work in one or more background threads, and whose state is observable and available to JavaFX applications and is usable from the main JavaFX Application thread.
People use the word "worker" when they mean a thread that does not own or interact with UI. Threads that do handle UI are called "UI" threads. Usually, your main (primary) thread will be the thread that owns and manages UI. And then you start one or more worker threads that do specific tasks.
"Should I just start a thread & put it in sleep mode for 1 minute" Even if you want you want to go with traditional thread ( dont want to use executor Fremework) DO NOT USE SLEEP for waiting purpose as it will not release lock and its a blocking operation . DO USE wait(timeout) here.
Wrong Approach -
public synchronized void doSomething(long time) throws InterruptedException {
// ...
Thread.sleep(time);
}
Correct Approach
public synchronized void doSomething(long timeout) throws InterruptedException {
// ...
while (<condition does not hold>) {
wait(timeout); // Immediately releases the current monitor
}
}
you may want to check link https://www.securecoding.cert.org/confluence/display/java/LCK09-J.+Do+not+perform+operations+that+can+block+while+holding+a+lock
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