Created
October 20, 2021 05:08
-
-
Save CyberFlameGO/81df6ff2263697eb3a577e25aca6a68f to your computer and use it in GitHub Desktop.
Java volatility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class VolatileExample { | |
/* | |
ESSENTIALLY, WITHOUT VOLATILE THREADS OTHER THAN MAIN WON'T BE ABLE | |
TO FETCH THE MOST UPDATED VALUE FOR THIS VARIABLE AS IT IS FETCHING FROM | |
CPU CATCH, THEREFORE, TO SURPASS THIS, WE USE VOLATILE AS IT WILL FORCE | |
THE SYSTEM TO FETCH THE TARGET VARIABLE DIRECTLY FROM MAIN MEMORY. | |
*/ | |
private static volatile boolean x = false; | |
private static Thread thread(){ | |
final Runnable runnable = new Runnable(){ | |
@Override | |
public void run() { | |
/* | |
waits until X = TRUE then finishes | |
*/ | |
while(!x); | |
System.out.println("DONE! " + Thread.currentThread().getName()); | |
} | |
}; | |
return new Thread(runnable); | |
} | |
public static void main(String[] args) throws Exception{ | |
thread().start(); | |
thread().start(); | |
thread().start(); | |
Thread.sleep(1000); | |
x = true; | |
System.out.println("CHANGED! " + Thread.currentThread().getName()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment