0
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
if(executor.isShutdown()) {
    executor.scheduleAtFixedRate(helloRunnable, 0, 1, TimeUnit.SECONDS);
}

This piece of code is executed everytime a event happens, how do i make it only execute for the first time?(like, if the scheduler is starter, do not execute)

I tried using executor.isShutdown() but it does not work

  • [ScheduledExecutorService - Check if scheduled task has already been completed](https://stackoverflow.com/questions/21442322/scheduledexecutorservice-check-if-scheduled-task-has-already-been-completed) may be helpful. – Eskandar Abedini Jun 17 '22 at 18:37

1 Answers1

0
  1. You can use AtomicBoolean to manage access to the executor:
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    private static final AtomicBoolean IS_ACTIVE = new AtomicBoolean(false);

    private void startScheduler() {
        if (IS_ACTIVE.compareAndSet(false, true)) {
            executor.scheduleAtFixedRate(() -> {}, 0L, 5L, TimeUnit.SECONDS);
        }
    }
  1. Or you can use synchronized and lazy initialization to make it work:
    private volatile ScheduledExecutorService scheduler;

    public void startScheduler() {
        if (scheduler == null) {
            this.initAndStart();
        }
    }

    private synchronized void initAndStart() {
        if (scheduler == null) {
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.schedule(() -> log.info("Started, Thread: {}", Thread.currentThread().getName()), 0L, TimeUnit.SECONDS);
        }
    }

Note: It will try to block current class and threads which managed to call initAndStart will also cause blocking, but as soon as scheduler is initialized there will be no blocking

ArtemAgaev
  • 78
  • 7