I have some jobs running to start periodically some business process, but I want to be able to stop these jobs before their end without killing the thread to be able to finish some other process after.
So I have a boolean isInterrupted
in my JobRunner
, which is set at true when I want to interrupt the job.
My Job is calling a service method, and this method is basically a big for each
(just to mention that this process should stay here and not be moved to the job). I want to stop this for
when the isInterrupted
variable is true.
Is there any way to pass this value by reference, or to pass a getter function as parameter as we could do in Javascript?
For information we are using in Java 8
CodePudding user response:
You can pass a BooleanSupplier
.
class Finisher {
private volatile boolean finished = false;
public boolean isFinished() { return finished; }
}
class Runner {
public void run(BooleanSupplier finishedSupplier) {
while (!finishedSupplier.getAsBoolean()) {
// do work
}
}
public static void main() {
Runner runner = new Runner()
Finisher finisher = new Finisher();
runner.run(finisher::isFinished);
}
}
Of course, the finisher instance must somehow be able to update its finished
flag. The code here is just for illustrative purposes to show how the syntax would be used.
finisher::isFinished
is a method reference and is (more or less) equivalent to writing () -> finisher.isFinished()
.
CodePudding user response:
If you want to pass a reference to some external boolean that may change over time, there are two main ways to do it:
- Pass an
AtomicBoolean
. Changes to its internal value in one thread can be seen in another thread. - Pass a
Supplier<Boolean>
to the child thread, which is effectively a metod reference to some method that returns aBoolean
.
Edit: As pointed out by knittl, Java also has a BooleanSupplier
that returns a boolean
instead of a Boolean
. In this case, that would presumably be preferable.