Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using wait/notify should be a more efficient method. I also agree with the suggestion that using 'volatile' is not necessary and synchronizing on an alternative object would be wise to avoid conflicts.</p> <p>A few other suggestions:</p> <ul> <li>Start the thread elsewhere, starting from a static block is not good practice</li> <li>Putting the execute logic in an "execute()" method or similar would be desirable</li> </ul> <p>This code implements the above suggestions. Note also that there is only the one thread performing the SomeService execution logic and that it will occur INTERVAL milliseconds after the time it last completed. You should not get duplicate executions after a manually triggered wakeUp() call.</p> <pre><code>public class SomeService implements Runnable { private static final INTERVAL = 15 * 1000; private Object svcSynchronizer = new Object(); private boolean running = true; private SomeService() { } public void run() { while (running) { try { // do what needs to be done // perhaps peeking at a blocking queue // or checking for records in a database // trying to be independent of the communication System.out.println("what needs to be done"); // wait for 15 seconds or until notify try { svcSynchronizer.wait(INTERVAL); } catch (InterruptedException e) { // ignore interruptions } } catch (Exception e) { e.printStackTrace(); } } } public void wakeUp() { svcSynchronizer.notifyAll(); } public void shutdown() { running = false; svcSynchronizer.notifyAll(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload