Created
July 20, 2014 07:09
-
-
Save adohe-zz/2878fe9bc2f39e55da13 to your computer and use it in GitHub Desktop.
volatile and synchronization in Java
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
| 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