Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created July 20, 2014 07:09
Show Gist options
  • Select an option

  • Save adohe-zz/2878fe9bc2f39e55da13 to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/2878fe9bc2f39e55da13 to your computer and use it in GitHub Desktop.
volatile and synchronization in Java
package com.ado.java;
/**
* Not Thread Safe
*/
public class MutableInteger {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
/**
* Thread Safe
*/
class SynchronizedInteger {
private int value;
public synchronized int getValue() {
return value;
}
public synchronized void setValue(int value) {
this.value = value;
}
}
class Volatile {
private static volatile boolean asleep;
private static void countSleep() {
// Stuff
}
public static void main(String[] args) {
while (!asleep) {
countSleep();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment