Skip to content

Instantly share code, notes, and snippets.

@GrmpCerber
Created July 9, 2013 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GrmpCerber/5956460 to your computer and use it in GitHub Desktop.
Save GrmpCerber/5956460 to your computer and use it in GitHub Desktop.
pooling test using a single synchronized instance. based on http://stackoverflow.com/a/13914445/233906
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class Share {
private static final int NB_LOOPS = 100000;
final static int NB_THREADS = 100;
final byte[] bytes = new byte[100];
final ExecutorService pool;
static MessageDigest digest;
static final AtomicLong grandTotal = new AtomicLong(0);
Share() throws NoSuchAlgorithmException {
digest = MessageDigest.getInstance("MD5");
pool = Executors.newFixedThreadPool(NB_THREADS);
}
void go() {
for (int i = 0; i < NB_THREADS; i++) {
pool.execute(new Runnable() {
public void run() {
long start = System.currentTimeMillis();
for (int i = 0; i < NB_LOOPS; i++) {
try {
synchronized (digest) {
digest.update(bytes);
digest.digest();
}
} catch (Exception ex) {
ex.printStackTrace();
}
Thread.yield();
}// fin for
long end = System.currentTimeMillis();
System.out.println(end - start);
grandTotal.addAndGet(end - start);
pool.shutdown();
}
});
}
}
public static void main(String[] args) throws Exception {
Share share = new Share();
share.go();
share.pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
System.out.println(grandTotal.get() + " ms");
System.out.println(TimeUnit.MILLISECONDS.toSeconds(grandTotal.get())
+ " s");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment