1

I have a

 ThreadPoolExecutor cachedPool = (ThreadPoolExecutor)Executors.newCachedThreadPool();

The cachededPool has to perform the following functionality in the main SimController class.

Run method for a watcher thread. Once per Second, check and call a function.

public void run(){
            if(m.isChanged()){
                m.toString();
            }                   
    }

But it only executes the run method once. How can I make it run every second and create a watcher.

Ahsan Ali
  • 109
  • 1
  • 11
  • 2
    You need to use https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate-java.lang.Runnable-long-long-java.util.concurrent.TimeUnit- on a ScheduledExecutorService. – Peter Lawrey Mar 10 '17 at 21:48
  • What is the purpose of the `m.toString();` expression? Why is the value of the expression ignored? – Lew Bloch Mar 10 '17 at 21:56
  • Its an object of a MemManager class. It displays the state of memory in a specific format. – Ahsan Ali Mar 10 '17 at 22:08

3 Answers3

0

You can use ScheduledExecutorService.scheduleAtFixedRate() as suggested by Peter Lawrey in a comment, or you can do the following:

public void run() throws InterruptedException {
    for( ;; ) {
        if( m.isChanged() ) //hopefully m is thread-safe
            m.toString();   //hopefully something more meaningful here
        Thread.sleep( 1000 ); //1000 milliseconds is one second.
    }
}

Note: if your run() method cannot throw InterruptedException, then you need to handle the InterruptedException that may be thrown by Thread.sleep(). A quick and dirty way to do this is to just say try{ ... } catch( InterruptedException e ) { throw new AssertionError( e ); } but if you want to do it the proper way, then be sure to read this: Handling InterruptedException in Java

Community
  • 1
  • 1
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • I know this is sample code @mike but in case you care, `run()` doesn't throw exceptions. – Gray Mar 10 '17 at 22:21
  • @Gray thanks. I wanted to avoid having to explain how to handle `InterruptedException`. I settled for an interim solution which simply points to another answer. – Mike Nakis Mar 10 '17 at 22:28
  • There's a possible down-side to this suggestion: It dedicates an entire thread to mostly sitting around waiting, doing nothing. I've written lots of threads that do pretty much the same thing, but it might be undesirable on a high-performance system that pushes the limits of the available hardware. – Solomon Slow Mar 10 '17 at 22:35
  • @jameslarge you are right. But I suspect that this is waaaay beyond the concerns of the OP. C-:= – Mike Nakis Mar 10 '17 at 22:36
  • People use `InterruptedException` so poorly that I make sure I _do_ explain it every time @Mike. Thanks. – Gray Mar 13 '17 at 14:27
0

The ScheduledExecutorService makes this pretty simple as this example, which prints the date every second, shows:

public class MonitorService {
    public static void main(String[] a) throws Exception {
        ScheduledExecutorService service = 
                Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(() -> {
            System.out.println(LocalDateTime.now());
        }, 0, 1, TimeUnit.SECONDS);
    }
}

If you have multiple jobs to schedule in your system you would want to share the scheduled executor service among all tasks for efficiency.

BarrySW19
  • 3,759
  • 12
  • 26
0

If you are using Spring then you could also use @Scheduled task over a method to run a scheduled task.

@Component
@EnableScheduling
public class TestClass {
    @Scheduled(fixedRate= 1000 , initialDelay = 18000)
    public void TestMethod(){
       // Do Something

    } }
Ayush Soni
  • 61
  • 4