Shlrm.org Blag

Groovy Threading and Java Threading

by David Kowis on Nov.30, 2009, under Coding!, Groovy

I must be doing something wrong regarding my groovy code. I was talking to a friend and fiddling with a tower of hanoi solver code. Just burns in CPU basically. Now I hacked it up in groovy, after he talked about it, just because. Well I came up with a groovy-ish solution that should do the same thing his java code did. However, the Java code actually ran like 8 threads, whereas my groovy code only ran about 3. Based entirely on CPU usage in linux. On the same box. I don’t understand… The code follows.

Groovy Code:

import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.Executors
import java.util.concurrent.Callable

def moveSingleDisk(source, dest) {
	//nothing!
}

def moveTower(number, source, dest, temp) {
	if (number > 0) {
		moveTower(number -1, source, temp, dest)
		moveSingleDisk(source, dest)
		moveTower(number - 1, temp, dest, source)
	}
}

AtomicInteger counter = new AtomicInteger()
counter.set(1)

synchronized out(message) {
	println message
}

def logic = {
	start = System.nanoTime()
	moveTower(it, 'A','B','C')
	stop = System.nanoTime()
	out("${it} took ${(stop-start)/ 10**6} milliseconds")
}

def THREADS=16

pool = Executors.newFixedThreadPool(THREADS)
println "Creating a pool for $THREADS threads"

1.upto(64) {
	def value = it
	//out "Submitting job $value"
	task = {c -> pool.submit( c as Callable)}
	task{logic(value)}
}

pool.shutdown()

Java code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hanoi2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author brad
 */
public class Main {

	static private ExecutorService exec = Executors.newFixedThreadPool(8);

	static void moveSingleDisk(char src, char dst) {
		// System.out.println(src + " => " + dst);
	}

	static void moveTower(int n, char src, char dst, char tmp) {
		if (n > 0) {
			moveTower(n - 1, src, tmp, dst);
			moveSingleDisk(src, dst);
			moveTower(n - 1, tmp, dst, src);
		}
	}

	public void run() {
	}

	public static void main(String[] args) {

		System.out.println("Starting with a thread pool of 8");

		for (int i = 0; i < = 64; i++) {
//      long start, stop;
			final int blah = i;
			exec.submit(new Runnable() {
				public void run() {
					long start = System.nanoTime();
					moveTower(blah, 'A', 'B', 'C');
					long stop = System.nanoTime();
					System.out.println(blah + " took " + ((stop - start) / 1000000) + "ms");

				}
			});
		}
	}
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • StumbleUpon
  • LinkedIn
  • TwitThis
:, ,

Leave a Reply

Archives

Hacker’s Diet

The Hacker's Diet Online