Java volatile keyword example for shared cache

A classic example of volatile keywords in java : If you run runLoop() in one thread and call stop() from another, the runLoop thread might stay in an infinite loop, the reason is only local cache update not a shared cache , so if we want to update shared cache we can use volatile like : private volatile boolean keepRunning = true class Task { private boolean keepRunning = true; public void stop() { keepRunning = false; System.out.println("Stop requested..."); } public void runLoop() { System.out.println("Loop started..."); while (keepRunning) { } System.out.println("Loop stopped!"); } } #Java #BackendDevelopment #SoftwareEngineering #MultiThreading #Concurrency #JavaPerformance #CodingTips #Programming #SystemDesign

check with this also volatile array

Like
Reply

To view or add a comment, sign in

Explore content categories