I have a line that runs a task repeatedly on a schedule:
executor.scheduleAtFixedRate(() -> Task.scanTask(task), 0, scanEvery, unit);
My question is, does that "task" parameter from the local variable get passed on every execution? or is it cached by the executor, so that changes to the local variable never make it to scanTask on next scheduled execution?
And is it bad practice to depend on each threads access to the current local value (not thread safe)?
CodePudding user response:
Since the code is using Lambda expression, the variable task
will have to be effectively a constant. I.e. it does not have to be a final variable, but its value should only be set once before the lambda, and then should never change. And that same task
object will be processed again and again in the threads.
Now, if the task
object itself is a list or has a list inside, and if that keeps changing, then when the thread is triggered, whatever values are there in the list, those will be processed.