Created
January 4, 2012 11:29
-
-
Save Afforess/1559655 to your computer and use it in GitHub Desktop.
synchronized test
This file contains 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 Main { | |
public static void main(String[] args) { | |
MyThreadUnsafeTestObject o1 = new MyThreadUnsafeTestObject(); | |
MyThreadSafeTestObject o2 = new MyThreadSafeTestObject(); | |
long start = System.nanoTime(); | |
for (int i = 0; i < 1000000; i++) { | |
o1.foo(); | |
} | |
System.out.println("Unsynchronized calls took " + (System.nanoTime() - start) / 1E6D + " ms"); | |
start = System.nanoTime(); | |
for (int i = 0; i < 1000000; i++) { | |
o2.foo(); | |
} | |
System.out.println("Synchronized calls took " + (System.nanoTime() - start) / 1E6D + " ms."); | |
} | |
} | |
class MyThreadUnsafeTestObject { | |
public double d; | |
public void foo() { | |
double d = 4 * Math.sinh(3.1D) * Math.pow(20, 1.74D) * 1000; | |
while (d > Math.PI) { | |
d = d / Math.pow(d, Math.PI); | |
} | |
this.d = d; | |
if (this.d != 1.5887418471800228E-15) { | |
throw new RuntimeException(); | |
} | |
} | |
} | |
class MyThreadSafeTestObject { | |
public double d; | |
public synchronized void foo() { | |
double d = 4 * Math.sinh(3.1D) * Math.pow(20, 1.74D) * 1000; | |
while (d > Math.PI) { | |
d = d / Math.pow(d, Math.PI); | |
} | |
this.d = d; | |
if (this.d != 1.5887418471800228E-15) { | |
throw new RuntimeException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment