0

I have a Java application which consists of three main threads:

  1. The main thread handling the user input, and starting the following threads.
  2. The thread which computes something, utilizes the CPU at 70-80%.
  3. The "monitor" thread, which should run in every 2 seconds, and read 1 short line from a file.

My issue is that the 3rd thread is not running properly. It starts to execute at the same time when the 2nd does, but in the meanwhile gets suspended, and gets resumed only after the 2nd thread finished.

I'm using ExecutorService for the 2nd thread, and ScheduledExecutorService for the monitoring thread. Here is my code:

ExecutorService executorService = Executors.newSingleThreadExecutor();
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

public void startThreads() {
    startMonitorThread();
    startCPUIntensiveThread();
}

public void startMonitorThread() {
    System.out.println("### Monitor started");

    Runnable monitor = () -> {
        readFileContent()
        System.out.println("hello from monitor");
    };

    // run the monitor in every 2s
    scheduledExecutorService.scheduleAtFixedRate(monitor, 0, 2, TimeUnit.SECONDS);

    System.out.println("### Monitor scheduled");
}

public void startCPUIntensiveThread() {
    Runnable runBenchmark = () -> {
        try {
            MyBenchmarkRunner.runBenchmark(); // runs 5 iterations, each takes 4 seconds
        } catch (Exception e) {
            System.err.println("Benchmark failed. See the log for more details."); 
        }
    };

    executorService.submit(runBenchmark);
}

And the output:

### Monitor started
### Monitor scheduled
hello from monitor // monitor scheduled and executed
===== Running benchmark iteration 1 =====
===== Running benchmark iteration 2 =====
===== Running benchmark iteration 3 =====
===== Running benchmark iteration 4 =====
===== Running benchmark iteration 5 ===== // at least 20 seconds passed
hello from monitor // monitor executed again, but it should have been executed 2x during each benchmark iteration
hello from monitor

How should I modify the code to ensure that the monitor thread is called in every 2 seconds?

Alex
  • 258
  • 2
  • 20

0 Answers0