Java Reference
In-Depth Information
they are already loaded into the core's cache, then that memory access is very, very fast—a
big performance win.
The downside to this scheme is that whenever the program updates a value in its local cache,
that core must notify all the other cores that the memory in question has been changed. Those
other cores must invalidate their cache lines and reload that data from memory.
Let's see what happens if the DataHolder class is heavily used by multiple threads:
public
public class
class ContendedTest
ContendedTest extends
extends Thread {
private
private static
static class
class DataHolder
DataHolder {
private
private volatile
volatile long
long l1 = 0 ;
private
private volatile
volatile long
long l2 = 0 ;
private
private volatile
volatile long
long l3 = 0 ;
private
private volatile
volatile long
long l4 = 0 ;
}
private
private static
static DataHolder dh = new
new DataHolder ();
private
private static
static long
long nLoops ;
public
public ContendedTest ( Runnable r ) {
super
super ( r );
}
public
public static
static void
void main ( String [] args ) throws
throws Exception {
nLoops = Long . parseLong ( args [ 0 ]);
ContendedTest [] tests = new
new ContendedTest [ 4 ];
tests [ 0 ] = new
new ContendedTest (() -> {
for
for ( long
long i = 0 ; i < nLoops ; i ++) {
dh . l1 += i ;
}
});
tests [ 1 ] = new
new ContendedTest (() -> {
for
for ( long
long i = 0 ; i < nLoops ; i ++) {
dh . l2 += i ;
}
});
//...similar for 2 and 3...
long
long then = System . currentTimeMillis ();
for
for ( ContendedTest ct : tests ) {
ct . start ();
}
for
for ( ContendedTest ct : tests ) {
ct . join ();
}
long
long now = System . currentTimeMillis ();
Search WWH ::




Custom Search