Shlrm.org Blog

Linux, Java, Ruby, and Politics

Groovy Threading and Java Threading

| Comments

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 Threading Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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 Threading Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * 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");

        }
      });
    }
  }
}

Comments