Created
May 14, 2012 00:19
-
-
Save na-ka-na/2690898 to your computer and use it in GitHub Desktop.
Memoize usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
import java.util.concurrent.*; | |
import lombok.Memoize; | |
public class MemoizeTest { | |
@Memoize | |
public static int test(final int k){ | |
System.out.println("test " + k); | |
return k+2; | |
} | |
@Memoize | |
public static int fib(final int n){ | |
if (n <= 1) return n; | |
return fib(n-1) + fib(n-2); | |
} | |
public static void main(String[] args) throws InterruptedException { | |
System.out.println(test(100)); | |
System.out.println(test(200)); | |
System.out.println(test(100)); | |
System.out.println(test(200)); | |
final Random r = new Random(); | |
Runnable run = new Runnable() { | |
@Override | |
public void run() { | |
for (int i=0; i<10000000; i++){ | |
int k = r.nextInt(20); | |
assert(test(k) == (k+2)); | |
} | |
System.out.println("Done " + Thread.currentThread().getName()); | |
} | |
}; | |
int nt = 10; | |
ExecutorService es = Executors.newFixedThreadPool(nt); | |
for (int i=0; i<nt; i++) | |
es.execute(run); | |
es.shutdown(); | |
while (!es.isTerminated()) | |
es.awaitTermination(1000, TimeUnit.MILLISECONDS); | |
int f = fib(42); | |
System.out.println(f); | |
} | |
} | |
/* Output | |
test 100 | |
102 | |
test 200 | |
202 | |
102 | |
202 | |
test 6 | |
test 12 | |
test 17 | |
test 7 | |
test 9 | |
test 15 | |
test 5 | |
test 13 | |
test 18 | |
test 2 | |
test 1 | |
test 3 | |
test 0 | |
test 10 | |
test 16 | |
test 8 | |
test 19 | |
test 14 | |
test 11 | |
test 4 | |
Done pool-1-thread-1 | |
Done pool-1-thread-8 | |
Done pool-1-thread-9 | |
Done pool-1-thread-2 | |
Done pool-1-thread-10 | |
Done pool-1-thread-6 | |
Done pool-1-thread-4 | |
Done pool-1-thread-5 | |
Done pool-1-thread-7 | |
Done pool-1-thread-3 | |
267914296 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment