Skip to content

Instantly share code, notes, and snippets.

@Afforess
Created January 4, 2012 11:29
Show Gist options
  • Save Afforess/1559655 to your computer and use it in GitHub Desktop.
Save Afforess/1559655 to your computer and use it in GitHub Desktop.
synchronized test
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