I have a web application which serves a lot of requests at the same time. In one of the app's API methods, I have a method - methodA(). In this method, I have a call to another method - doSomething(). I have a scenario in which I want the first call to methodA() will run the doSomething() method in a separate thread, but at this time, if another call to methodA() has been called, don't run the doSomething() method (because its still running by another thread) and just continue with the rest of methodA().
methodA() {
.
.
doSomething() // In a new thread
.
.
}
I've considered using atomic boolean as a flag but I'm not sure if it's the best idea.
private final AtomicBoolean isOn = new AtomicBoolean(false);
methodA() {
.
.
if (isOn.compareAndSet(false, true)) {
Runnable doSomethingRunnableTask = () -> {
doSomething(); };
Thread t1 = new Thread(doSomethingRunnableTask);
t1.start();
isOn.set(false);
}
Thanks!