Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

What is Headless mode in Java

58 sec read

Java contains a lot of classes which assume that there is a some sort of display and a keyboard attached. Sometimes, you are writing code to run on a server which does not have these and this is called Headless mode. Since Java 1.4 you have been able to explicitly tell Java to run in Headless mode with

System.setProperty("java.awt.headless", "true");

This can cause issues with some Java code, especially Swing (which was designed for display and much of which assumes there is a display device attached).

So Sun/Oracle have a option to tell if the code is running in Headless mode, and avoid using GUI components if you have no display. You can find out by using the GraphicsEnvironment class and calling the static method isHeadless(). If you try and create Swing components in Headless mode you will get a Headless exception.

There are some GUI components you could need in Headless mode (for Example Canvas so that you can print), so a subset of Swing components will run in Headless mode (essentially Canvas, Panel, Image and Font classes).

So if your code might run in Headless mode, you need to ensure that Swing components such as Lists, Frames, Buttons are only initialised if there is a Display available. You might even consider following the approach we have adopted for our Java PDF library where we have a PdfDecoder class designed to run on systems with a display and a PdfDecoderServer class alternative (with the same API), specifically setup to run on Headless  systems.

If you are looking for more information, Oracle have an excellent reference article here.

 

Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

Leave a Reply

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

IDRsolutions Ltd 2019. All rights reserved.