Skip to content

Instantly share code, notes, and snippets.

@jkutner
Created January 4, 2011 15:09
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 jkutner/764875 to your computer and use it in GitHub Desktop.
Save jkutner/764875 to your computer and use it in GitHub Desktop.
import akka.stm.*;
import java.util.concurrent.*;
import java.util.*;
public class TestStm {
public static Vector<Ref<Integer>> testStm(final int nitems, final int nthreads, final int niters)
throws Exception {
final Vector<Ref<Integer>> refs = new Vector<Ref<Integer>>(nitems);
for (int i=0; i<nitems; i++) {refs.add(new Ref<Integer>(0));}
ExecutorService pool =
Executors.newFixedThreadPool(nthreads);
List<Callable<Void>> tasks =
new ArrayList<Callable<Void>>(nthreads);
for (int x=0; x<nthreads; x++) {
final int t = x;
tasks.add(new Callable<Void> () {
public Void call() {
for (int n=0; n<niters; n++) {
new Atomic<Void>() {
public Void atomically() {
for (int r=0; r<refs.size(); r++) {
refs.get(r).set(1+t+refs.get(r).get());
}
return null;
}
}.execute();
}
return null;
}
});
}
for (Future f : pool.invokeAll(tasks)) {f.get();};
pool.shutdown();
return refs;
}
public static void main(String[] args) throws Exception {
Vector<Ref<Integer>> refs = testStm(10,10,10000);
for (Ref<Integer> r : refs) {
System.out.println(r.get());
}
}
}
(import '(java.util.concurrent Executors))
(defn test-stm [nitems nthreads niters]
(let [refs (map ref (replicate nitems 0))
pool (Executors/newFixedThreadPool nthreads)
tasks (map (fn [t]
(fn []
(dotimes [n niters]
(dosync
(doseq [r refs]
(alter r + 1 t))))))
(range nthreads))]
(doseq [future (.invokeAll pool tasks)]
(.get future))
(.shutdown pool)
(map deref refs)))
(test-stm 10 10 10000)
import java.util.concurrent.*;
import java.util.*;
class Main {
public static Vector<Integer> testStm(
final int nitems, final int nthreads, final int niters)
throws Exception {
final Vector<Integer> refs = new Vector<Integer>(nitems);
for (int i=0; i<nitems; i++) {refs.add(0);}
ExecutorService pool =
Executors.newFixedThreadPool(nthreads);
List<Callable<Void>> tasks =
new ArrayList<Callable<Void>>(nthreads);
for (int x=0; x<nthreads; x++) {
final int t = x;
tasks.add(new Callable<Void> () {
public Void call() {
for (int n=0; n<niters; n++) {
for (int r=0; r<refs.size(); r++) {
refs.set(r,1+t+refs.get(r));
}
}
return null;
}
});
}
for (Future f : pool.invokeAll(tasks)) {f.get();};
pool.shutdown();
return refs;
}
public static void main(String[] args) throws Exception {
testStm(10,10,10000);}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment