'Is there a possibility to make main thread wait when the scheduledExecutorService process is running scheduleWithFixedDelay

I need to monitor the property value has changed or not throughout the java program run, if its value has changed in need to do some necessary steps to handle the changed value.

I have used scheduleWithFixedDelay service to monitor value and observer pattern to take necessary action.

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleWithFixedDelay(() -> {
    myClass2.scanValueChanged();
},1,45, TimeUnit.SECONDS);

Since scheduledExecutorService and main thread run parallel, by the time I handled in scheduledExecutorService the main method runs executes the block of the code and fails with the expected outcome.

Is there a way when scheduledExecutorService is running that I can pause the main thread?



Solution 1:[1]

Just use the main thread

If your app has nothing else to do, then why use an executor service? With no other work for the main thread, there’s no need for background threads.

Call myClass2.scanValueChanged() on your main thread, followed by Thread.sleep( 45 * 1_000 ), in a loop that repeats until your condition is met.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1