Worker Thread in Java

后端 未结 4 2160
天命终不由人
天命终不由人 2021-02-08 07:13

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

4条回答
  •  执念已碎
    2021-02-08 07:32

    "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 () {
        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

提交回复
热议问题