Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Worker Thread in Java

Tags:

java

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!

like image 717
Mike Avatar asked Dec 20 '11 07:12

Mike


People also ask

What is a worker thread in Java?

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.

What are worker threads?

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.

What is worker in Java?

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.

What is worker thread and main 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.


1 Answers

"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

like image 158
Vipin Avatar answered Sep 22 '22 19:09

Vipin