Skip to content
Advertisement

Using volatile for skipping method execution

I’ve never used volatile very often. Is it possible to use it to skip method execution if another thread executing it? I think in the code below it’s still possible that multiple threads pass the check and execute the method. Isn’t it?

JavaScript

Use case: The method can be run periodically but at the same time it can be triggered manually by a user. There is no reason to run it twice one after another by using synchronized keyword. Please, tell me it’s doable with volatile. Otherwise I don’t see any reason to understand it except for job interviews 🙂 Other solutions that aren’t based on volatile are welcome.

Advertisement

Answer

You can use a volatile AtomicBoolean, like this, to achieve your requirement.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement