Skip to content

Instantly share code, notes, and snippets.

@revbingo
Created February 24, 2015 22:45
Show Gist options
  • Save revbingo/4c035aa29d3c7b50ed8b to your computer and use it in GitHub Desktop.
Save revbingo/4c035aa29d3c7b50ed8b to your computer and use it in GitHub Desktop.
StackOverflow - why does this code run faster when it's synchronized?
package co.wds.visualvm;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
//you will need to add commons-math-3.4.1 to the classpath
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.random.GaussianRandomGenerator;
import org.apache.commons.math3.random.JDKRandomGenerator;
import org.apache.commons.math3.random.StableRandomGenerator;
import org.apache.commons.math3.random.UncorrelatedRandomVectorGenerator;
public class Main {
private static ExecutorService exec = Executors.newFixedThreadPool(2);
private static long startTime;
private final static int MATRIX_SIZE = 500;
private static UncorrelatedRandomVectorGenerator generator = new UncorrelatedRandomVectorGenerator(MATRIX_SIZE, new StableRandomGenerator(new JDKRandomGenerator(), 0.1d, 1.0d));
// private static UncorrelatedRandomVectorGenerator generator = new UncorrelatedRandomVectorGenerator(MATRIX_SIZE, new GaussianRandomGenerator(new JDKRandomGenerator()));
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
start();
for(int i=0; i < 100; i++) {
exec.execute(new Runnable() {
@Override
public void run() {
double[][] matrixArrayA = new double[MATRIX_SIZE][MATRIX_SIZE];
double[][] matrixArrayB = new double[MATRIX_SIZE][MATRIX_SIZE];
for(int j = 0; j< MATRIX_SIZE; j++) {
matrixArrayA[j] = generator.nextVector();
matrixArrayB[j] = generator.nextVector();
}
RealMatrix matrixA = MatrixUtils.createRealMatrix(matrixArrayA);
RealMatrix matrixB = MatrixUtils.createRealMatrix(matrixArrayB);
lock.lock();
matrixA.multiply(matrixB);
lock.unlock();
}
});
}
stop();
}
public static void start() {
startTime = System.currentTimeMillis();
System.out.println("Starting Tasks...");
}
public static void stop() {
try {
exec.shutdown();
boolean finishedNicely = exec.awaitTermination(30, TimeUnit.SECONDS); //blocks until tasks have finished, or 30 seconds have passed. Change timeout if you run more tasks
if(finishedNicely) {
long total = System.currentTimeMillis() - startTime;
System.out.printf("Processed tasks in %.3f seconds", ((double)(total/1000d)));
} else {
System.out.printf("Didn't finish nicely, timed out :(");
System.exit(0);
}
} catch (InterruptedException e) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment