<clinit> in The Thread of First Use

Question: In which thread does <clinit> run?

Answer: is being executed in whatever thread uses the class first.

package testers;

import java.awt.EventQueue;

public class CLInit {
public static void main(String[] args) throws Exception {
new CLInit2().doSomething();
EventQueue.invokeAndWait(new Runnable() {
public void run() {
new CLInit2().doSomething();
new CLInit3().doSomething();
}
});
new CLInit3().doSomething();
}
}

class CLInit2 {
static {
System.out.println("CLInit2.: "+Thread.currentThread());
}

public void doSomething() {
System.out.println("CLInit2.doSomething");
}
}

class CLInit3 {
static {
System.out.println("CLInit3.: "+Thread.currentThread());
}

public void doSomething() {
System.out.println("CLInit3.doSomething");
}
}

produces the output

$ java testers.CLInit
CLInit2.<CLInit>: Thread[main,5,main]
CLInit2.doSomething
CLInit2.doSomething
CLInit3.<CLInit>: Thread[AWT-EventQueue-0,6,main]
CLInit3.doSomething
CLInit3.doSomething

As you can see, the class initializer for CLInit2 is run in the main thread, but the one for CLInit3 is executed in the event thread.

The implication of this is that class initializers may run in the event thread (or auxiliary threads) and therefore have to be considered when I compute the methods that are reachable in auxiliary threads or the event thread.

Share

About Mathias

Software development engineer. Principal developer of DrJava. Recent Ph.D. graduate from the Department of Computer Science at Rice University.
This entry was posted in Concurrent Unit Testing. Bookmark the permalink.

One Response to <clinit> in The Thread of First Use

  1. Pingback: A Concurrent Affair » Blog Archive » <clinit> in Which Thread?

Leave a Reply