怎么样避免伪共享呢?
一个典型的例子就是lmax disruptor中的缓存行填充技术。假设cache line的大小是64字节,一个cache line能容纳8个long型变量,disruptor中的做法是在long变量的前面和后面分别填充7个long变量,这样就可以避免我们需要的变量和其他变量在同一个cache line,解决伪共享问题。(当变量类型不是long的时候,我们要在此变量前后填充一些变量,使其从前面填充变量到此变量的长度和从此变量到后面填充变量均为缓存行的长度大小)
用例如下
public final class FalseSharing implements Runnable
{
public final static int NUM_THREADS = 4; // change
public final static long ITERATIONS = 500L * 1000L * 1000L;
private final int arrayIndex;
private static VolatileLong[] longs = new VolatileLong[NUM_THREADS];
static
{
for (int i = 0; i < longs.length; i++)
{
longs[i] = new VolatileLong();
}
}
public FalseSharing(final int arrayIndex)
{
this.arrayIndex = arrayIndex;
}
public static void main(final String[] args) throws Exception
{
final long start = System.nanoTime();
runTest();
System.out.println("duration = " + (System.nanoTime() - start));
}
private static void runTest() throws InterruptedException
{
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < threads.length; i++)
{
threads[i] = new Thread(new FalseSharing(i));
}
for (Thread t : threads)
{
t.start();
}
for (Thread t : threads)
{
t.join();
}
}
public void run()
{
long i = ITERATIONS + 1;
while (0 != --i)
{
longs[arrayIndex].value = i;
}
}
public final static class VolatileLong
{
public volatile long value = 0L;
public long p1, p2, p3, p4, p5, p6; // comment out
}
}