Maxim Kirilov Maxim Kirilov - 26 days ago 8
Java Question

Is it possible to improve code by using variable padding to avoid cache contention?

I recently attended an interview where in a question was asked "Is it possible to improve the following code":

public class Performance{
static class C1 {
volatile long c1;
volatile long c2;
}

static C1 p = new C1();

static class Worker implements Runnable {

private static final int INT = Integer.MAX_VALUE / 8;
private final boolean b;

Worker(boolean b) {
this.b = b;
}

@Override
public void run() {
if (b) {
for (int i = 0; i < INT; i++) {
p.c1++;
}
} else {
for (int i = 0; i < INT; i++) {
p.c2++;
}
}
}
}

public static void main(String[] args) {
Thread t1 = new Thread(new Worker(true));
Thread t2 = new Thread(new Worker(false));
t1.start();
t2.start();
}

}

Answer

JIT compiler from java 7 is very smart. It removes or reorders of unused field. For avoid false sharing you should add volatile key work.

Java 8 has new annotation @sun.misc.Contented. http://shipilev.net/talks/jvmls-July2013-contended.pdf