Maxim Kirilov Maxim Kirilov - 1 year ago 68
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;

public void run() {
if (b) {
for (int i = 0; i < INT; i++) {
} else {
for (int i = 0; i < INT; i++) {

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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download