Skip to content

Instantly share code, notes, and snippets.

@w1shen
Created April 17, 2013 05:45
Show Gist options
  • Save w1shen/5402044 to your computer and use it in GitHub Desktop.
Save w1shen/5402044 to your computer and use it in GitHub Desktop.
atomic write: 25377ms, synchronized write: 56757ms, atomic read: 639ms, synchronized read: 56181ms, volatile read: 43ms, normal read: 640ms,
package pig.pigtest;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
public class AtomicTest {
private AtomicLong v1 = new AtomicLong(0);
private long v2 = 0;
private volatile long v3 = Integer.MAX_VALUE;
private long v4 = Integer.MAX_VALUE;
public long incr1() {
return v1.getAndIncrement();
}
public synchronized long incr2() {
return v2++;
}
public long get1() {
return v1.get();
}
public synchronized long get2() {
return v2;
}
public long get3() {
return v3;
}
public long get4() {
return v4;
}
@Test
public void testAtomicLong() {
int count = Integer.MAX_VALUE;
long s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
incr1();
}
System.out.printf("atomic write: %sms%n", System.currentTimeMillis() - s);
s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
incr2();
}
System.out.printf("synchronized write: %sms%n", System.currentTimeMillis() - s);
s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
get1();
}
System.out.printf("atomic read: %sms%n", System.currentTimeMillis() - s);
s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
get2();
}
System.out.printf("synchronized read: %sms%n", System.currentTimeMillis() - s);
s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
get3();
}
System.out.printf("volatile read: %sms%n", System.currentTimeMillis() - s);
s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
get4();
}
System.out.printf("normal read: %sms%n", System.currentTimeMillis() - s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment