- 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);
}
}
- 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