Java puzzle 1: fun with Loggers

I’ve been a fan of Java Puzzlers by Joshua Bloch and Neal Gafter since a colleague lent me a copy about a year ago. Every now and again, I come across weird things in Java that I think would make a good puzzle.

In the spirit of Java Puzzlers, consider the following piece of code. It takes a single command line argument, which is an integer. What is the expected output for inputs of 100000 and 1000000 (i.e. 10^5 and 10^6)?


import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class Test {
	public static void main(String[] args) {
		addHandler();
		int numObjects = Integer.parseInt(args[0]);
		for (int i = 0; i < numObjects; i++) {
			new Object();
		}
		Logger logger = Logger.getLogger("test");
		logger.log(Level.INFO, "Hello world");
	}

	private static void addHandler() {

		Logger logger = Logger.getLogger("test");
		logger.addHandler(new Handler() {
			@Override
			public void publish(LogRecord record) {
				throw new RuntimeException("Goodbye cruel world");
			}
			@Override
			public void flush() {
			}
			@Override
			public void close() throws SecurityException {
			}
		});
	}
}

Answer:
Show ▼

Leave a Reply

Your email address will not be published. Required fields are marked *