home | lab | find me | science | publications | software | toolbox | site map

Java tricks

Using instance initializer blocks to fill in a collection created as an anonymous class

import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class TestInstanceInitializer {

   static public void main(String[] args) {

       for (char c : new ArrayList<Character>() {{ add('a'); add('b'); add('c'); }}) {
           System.out.println("char: " + c);

       for (Map.Entry<Integer,String> e : new HashMap<Integer,String>() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}.entrySet()) {
           System.out.println(e.getKey() + " => " + e.getValue());


The above prints:

char: a
char: b
char: c
1 => one
2 => two
3 => three

Creating a list from an implicit array

import java.util.Arrays;
import java.util.List;

public class Test {
    static public void main(String[] args) {
        // Make a collection of characters from an array of char
        // Internally, the "asList" method collects all arguments
        // into an Object[] array, since each char gets promoted
        // to a Character (via automatic boxing/unboxing of primitives.)
        List<Character> list = Arrays.asList('a', 'b', 'c');

Static versus instance initializers of a java class:

public class Foo {

    /* Static initializer: executes when the class is loaded. */
    static {
        System.out.println("class Foo loaded!");

    /* Instance initializer: excutes when calling new Foo(),
      BEFORE anything inside the Foo constructor */
        System.out.println("new instance of Foo about to be created!");
        // has access to internal Foo methods:
        print("instance initializer has access to internal methods!");

    /* Constructor */
    public Foo() {
        System.out.println("Foo constructor statements!");

    public void print(String msg) {

    static public void main(String[] args) {
        new Foo();
        System.out.println(" ");
        new Foo();

The above prints (note the order!)

class Foo loaded!
new instance of Foo about to be created!
instance initializer has access to internal methods!
Foo constructor statements!

new instance of Foo about to be created!
instance initializer has access to internal methods!
Foo constructor statements!

How to debug a multithreaded java program

The purpose of his tutorial is to find thread deadlocks and the responsible source code lines.

Step 1: execute the program with the following JVM argument:


For example, to run ImageJ under debugging conditions:

$ java -Xmx1000m -classpath ij.jar -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n ij.ImageJ

Step 2: in a separate shell, call the java debugger (jdb) and attach it to the running java virtual machine that executes ImageJ:

$ jdb -attach 8000

Step 3: run whatever task in the java program until it locks up.

Step 4: go to the jdb prompt, and get the list of all threads by typing 'threads':

> threads
Group system:
  (java.lang.ref.Reference$ReferenceHandler)0x53d Reference Handler cond. waiting
  (java.lang.ref.Finalizer$FinalizerThread)0x53e  Finalizer         cond. waiting
  (java.lang.Thread)0x53f                         Signal Dispatcher running
  (java.lang.Thread)0x540                         Java2D Disposer   cond. waiting
Group main:
  (java.lang.Thread)0x542                         AWT-Shutdown      cond. waiting
  (java.lang.Thread)0x543                         AWT-Motif         running
  (java.awt.EventDispatchThread)0x544             AWT-EventQueue-0  cond. waiting
  (java.lang.Thread)0x545                         SocketListener    running
  (java.lang.Thread)0x546                         DestroyJavaVM     running
  (ini.trakem2.utils.Utils$LogDispatcher)0x555            Thread-1          cond. waiting
  (ini.trakem2.utils.Utils$StatusDispatcher)0x556         Thread-2          cond. waiting
  (ini.trakem2.persistence.Loader$ImageLoaderThread)0x7ea Thread-7          cond. waiting
  (ini.trakem2.persistence.Loader$Preloader)0x7ef         Thread-8          cond. waiting
  (ini.trakem2.display.DisplayNavigator$1)0x886           Thread-10         cond. waiting
  (ini.trakem2.display.DisplayCanvas$1)0x890              Thread-11         cond. waiting

Above, all threads listed as "waiting in a monitor" are locked up. Fortunately I have none :)

When it lists "cond. waiting" it means the thread is in a wait() call for an object, which will wait until it recieves a continue or wake up call from a notify() or notifyAll().

Step 5: get the thread stack trace, for which you need first to suspend the thread (or all threads). Simply call 'where <thread id>'. The id is listed as an octal number next to the thread class name above.

> suspend
All threads suspended.
> where 0x890
  [1] java.lang.Object.wait (native method)
  [2] java.lang.Object.wait (Object.java:485)
  [3] ini.trakem2.display.AbstractRepaintThread.run (AbstractRepaintThread.java:139)

The above will help you figure out where did the threads got locked up.

To figure out why they locked up, see below the section on "how to synchronize access to a variable".

A very useful method is the TrakEM2 Lock class, which reads like the following:

public class Lock {
    private boolean locked = false;
    static private boolean debug = false;
    public final void lock() {
        if (debug) Utils.printCaller(this, 7);
        while (locked) try { this.wait(); } catch (InterruptedException ie) {}
        locked = true;
    public final void unlock() {
        if (debug) Utils.printCaller(this, 7);
        locked = false;
    static public final void debug() {
        debug = true;

Above, the printCaller function is simply a way to get the stack trace dynamically. It is listed below.

An advantage of the Lock class is that you can activate debugging dynamically, for example from the Jython Interpreter for ImageJ, by calling Lock.debug().

Simply be sure to use it like:

public class Any {
    private final Lock lock = new Lock();

    public void doSomethingSynch() {
        synchronized (lock) {
            try {
                // Do whatever needs to be run under synchronized conditions
                // since only one thread at a time can access this block.
            catch (Exception e) {

[Thanks to Aneesh P. for making me write the above more clearly.]

Note that the code block is enclosed in a try - catch block, to ensure that the lock is always released in any case. Otherwise, you'd get a deadlock the next time a thread synchronizes on the lock object.

When debug is true, every time the lock is set by calling lock() on it you will see the stack trace in the terminal. Same for unlock().

Under normal conditions, you will see a list of lock and unlock printouts, alternating. When the program reaches a deadlock, you will see two or more lock calls printed consecutively. Gotcha! Just follow the stack traces into your source code logic.

How to trace who called a method and where

The idea is to use this method wherever there is a hard-core problem, such as a lock up of threads. For example if you have a method controling the locking and unlocking of a specific variable, the method below can tell you who is calling the locking method. You will see the locking method being printed twice consecutively, and voilà, you have it.

/** Print as many lines of the back trace as desired.*/
static public void printCaller(Object called_object, int lines) {
	StackTraceElement[] elems = new Exception().getStackTrace();
	if (elems.length < 3) {
		System.out.println("Stack trace too short for " + called_object);
	} else {
		StringBuffer sb = new StringBuffer()
		    .append("#### START TRACE ####\nObject ")
		    .append(" called at: ").append(elems[1].getFileName())
		    .append(" ").append(elems[1].getLineNumber())
		    .append(": ").append(elems[1].getMethodName())
		    .append("()\n    by: ")
		    .append(elems[2].getClassName()).append(" ")
		    .append(elems[2].getLineNumber()).append(": ")
		for (int i=3; i<lines+2 && i<elems.length; i++) {
			sb.append("\tby: ").append(elems[i].getClassName())
			  .append(" ").append(elems[i].getLineNumber())
			  .append(": ")
		sb.append("==== END ====");

How to synchronize access to a variable

What is intended is to prevent to concurrent threads from reading and/or writing from/to the same variable simultaneously, which would result in most unexpected outcomes -and most likely, and exception being thrown.

As easy as it seems, once the verbosity is abstracted away:

private Object lock = new Object();
private boolean locked = false;

private void lock() {
	while (locked) {
		try { lock.wait(); } catch (InterruptedException ie) {}
		locked = true;

private void unlock() {
	locked = false;

private void anyMethod() {
	synchronized(lock) {
		try {
			// do whatever to specific variables
			// whose access must be restricted
			// to a single thread at a time
			// ...
			// ...
		} catch (Exception e) {
		} finally {

You can use the synchronized block in as many methods as you wish; access to variables from within the block will be synchronized, i.e. accessed by a single thread at a time.

Just be careful to call unlock() as well before returning, if your method returns in the middle of the try { } catch statement. Otherwise all other threads entering a synchronized clause on the Object lock would get locked forever.

Key concepts regarding the synchronized keyword:

You may wonder what is the advantage of doing the above versus simply adding a synchronized keyword to the method declaration (such as: public synchronized void anyMethod() { ). Synchronizing a method will make any Thread calling the method to wait for, and grab, the lock of the instance on which the method is called upon (all object instances in Java have a lock built-in, by default). So any two threads trying to access two different methods which are both synchronized, will have to wait on each other even if the variables each method access don't collide at all.

Synchronizing an entire method may thus incur in severe performance drawbacks. For example, imagine your synchronized method is loading an image file. Since the entire method is synchronized, files can be loaded only one at a time, which defeats the purpose of paralelizing expensive imaging routines that depend on multiple files. A better alternative is to syncrhonize not the method, but the critical variables such as the tracker of memory in use, and the cache that stores the images. See for example the convoluted, yet nearly totally parallel image retrieval methods fetchImagePlus and fetchImageProcessor that TrakEM2 uses. Shared locks are only for global variables such as the cache image pointer list, which are very cheap and quick, whereas individual locks are created (and then deleted) on the fly for each file, so that the same file is not loaded twice.

Another alternative is to synchronize the variable itself (or rather, the class an intance of which is held in the variable). For example, the class java.util.Vector is fully synchronized. Adding or removing elements to/from a Vector does not need any further synchronization. But calling size() on a Vector, and then doing something meaningful with that size value is doomed to fail, because after calling size() the Vector may be modified any time, including immediately after. You may have to lock the Vector under a synchronized statement as explained above if you plan to make multiple subsequent calls to a Vector while expecting its slots not to change.

The above, by the way, can be further simplified by hiding most of it away into a simple class Lock. TrakEM2 contains numerous examples of its usage for controling access to a variable, for example in controling the queueing of repaint events..

Don't miss Sun's java web site for concurrency and synchronization.

How to fix the confusing Math.atan2 output

I don't know you, but it took me a couple hours to figure out that the returned value of Math.atan2 output -the angle of a vector- is pure nonsense. Or more precisely, unusable because of lack of continuity. Here is my patch for it:

/** Returns the angle in radians of the given polar coordinates
* correcting Math.atan2 output to a pattern I can digest.
* Adjusting so that 0 is 3 o'clock, PI+PI/2 is 12 o'clock,
* PI is 9 o'clock, and PI/2 is 6 o'clock */
static public double getAngle(double x, double y) {
	// calculate angle
	double a = Math.atan2(x, y);
	// fix too large angles (beats me why are they ever generated)
	if (a > 2 * Math.PI) {
		a = a - 2 * Math.PI;
	// fix atan2 output scheme to match my mental scheme
	if (a >= 0.0 && a <= Math.PI/2) {
		a = Math.PI/2 - a;
	} else if (a &lt; 0 && a >= -Math.PI) {
		a = Math.PI/2 -a;
	} else if (a > Math.PI/2 && a <= Math.PI) {
		a = Math.PI + Math.PI + Math.PI/2 - a;
	// return
	return a;

The code above applies as well to C and C++, with very minor modifications (remove the 'Math.', import the proper <math.h>.)

How to preserve the expanded status of nodes in a JTree

There is no official way to preserve the expanded or collapsed state of all nodes in a JTree, particularly of expanded nodes under a collapsed parent or super parent.

But there are hackerous ways to work around such limitation. After a little bit of testing, I have realized that the JTree field named

transient private Hashtable expandedState

is the exact required lever to push.

The problem lays at the ludicrous implementation of the method isExpanded(TreePath path) in the javax.swing.JTree class. Such method works, in practice, like the isVisible(Treepath path) method, because it checks whether any of the parents is also expanded. Never mind that the JTree remembers which nodes are expanded or collapsed even when hidden from view because any of the parents is collapsed.

My code aims at creating a method analogous to JTree's isExpanded(Treepath path) but which will not care whether the parents of the tested node are expanded or not. And here it is:

/** Method in a class that extends JTree, thus 'this' means this JTree. */
public boolean isExpanded(final TreePath path) {
        try {
                java.lang.reflect.Field f = JTree.class.getDeclaredField("expandedState");
                Hashtable ht = (Hashtable)f.get(this);
                return Boolean.TRUE.equals(ht.get(path));
        } catch (Exception e) {
        return false;

Later, to restore the expanded state of each node, one simply has to iterate over the recorded nodes whose value was a Boolean.TRUE in the expandedState Hashtable, and put a new entry in the table (after, again, retrieving it through reflection).

The approach above bypasses all security measures and may not work in untrusted applets (where the setAccessible(true) call will fail). In addition, the JTree method hasBeenExpanded(Treepath path), which records whether a node has ever been expanded, may not report properly. But I have no need for it and thus I blatanly decide to ignore it.

The above is hackerous, fragile and liable to brake in the future, but it works right now for java 1.4.2, java 1.5.0 and 1.6.0.

How to count the number of CPUs

What I do is to query /proc/stat and parse the text output. This solution is POSIX-only, which means that Windows will most likely not work - and the code below is written to return always 1 for Windows.

If you know of a better way I'd appreciate that you share it with me.

The code is written to do the query only once. The result is stored in a static variable n_CPUs and then returned by the same method.

static private isWindows = System.getProperty("os.name").startsWith("Windows");;

static private int n_CPUs = 0;

static public int getCPUCount() {
	if (n_CPUs > 0) return n_CPUs;
	if (isWindows) return 1; // no clue
	// POSIX systems, attempt to count CPUs from /proc/stat
	try {
		Runtime runtime = Runtime.getRuntime();
		Process process = runtime.exec("cat /proc/stat");
		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String line;
		n_CPUs = 0;
		// valid cores will print as cpu0, cpu1. cpu2 ...
		while ((line = br.readLine()) != null) {
			if (0 == line.indexOf("cpu") && line.length() > 3
			 && Character.isDigit(line.charAt(3))) {
		// fix possible errors
		if (0 == n_CPUs) n_CPUs = 1;
		return n_CPUs;
	} catch (Exception e) {
		Utils.log(e.toString()); // just one line
		return 1;

NOTE: I was told much later that java has it built-in: Runtime.getRuntime().availableProcessors() will tell you the number as well.

Generating a javadoc into a target folder

For the whole set of java libraries, into folder 'api':

$ mkdir src
$ mv src.zip src/
$ cd src/
$ unzip src.zip
$ mkdir api
$ javadoc -J-Xmx1000m -d api -subpackages com:java:javax:org:sunw

How to measure the width and height, in pixels, of a piece of text in a String, for a specific Font

static public Dimension getTextDimensions(String text, Component component, Font font) {
    FontMetrics fm = component.getFontMetrics(font);
    int[] ws = fm.getWidths(); // for the first 256 characters
    int height = fm.getHeight();
    int width = 0;
for (int i=text.length() -1; i>-1; i--) {
    int c = (int)text.chatAt(i);
    if (c < 256) {
        width += ws[c];
    } // else ignore character
    return new Dimension(width, height);

    String text = "some text";
    Font font = new Font("SansSerif", Font.PLAIN, 12);
    Component c = ...; // your window frame, for example, or a JLabel, etc.

    Dimension dim = getTextDimensions(text, c, font);

How to set the width of a cell in a JTable

JTable table = ...;
int column = ...; // the column index to set the width for
int width = ...;

TableColumnModel col_model = table.getColumnModel().getColumn(column);

// Also: col_model.setPrefferredWidth(width), but the latter won't usually do
// what you want unless you change parameters for every single table cell
// renderer.

Likely what you want to do is to adjust the cell width to that of the text that it contains. For that, we need to capture the renderer component of the cell, so we can read both its text and its Font:

int column = ...;
int row = ...;
Component cell = table.getDefaultRenderer(table.getModel().getColumnClass(column))
              .getTableCellRendererComponent(table, text, false, false, row, column);
String text = cell.getText();
Dimensions dim = getTextDimensions(text, cell, cell.getFont());

The function getTextDimensions is defined in the previous section.

Last updated: 2012-05-08 11:10 Zurich time. Copyright Albert Cardona.