What is the benefit of setting java.awt.headless=true?

user2250246 picture user2250246 · Dec 9, 2016 · Viewed 26.8k times · Source

I have gone through

  1. Setting java.awt.headless=true programmatically
  2. http://www.oracle.com/technetwork/articles/javase/headless-136834.html and
  3. Some other links too.

Nowhere it is explained the benefit of using this flag.

Is it a performance benefit? If yes, is there even a rough quntization how much performance benefit there will be? (I know that answers to performance questions totally depend upon case to case, but it would be nice to know if someone reported a good benefit from doing this).

Answer

rustyx picture rustyx · Jan 23, 2020

There is no performance benefit of setting java.awt.headless=true if you're not using AWT features. AWT features are loaded on-demand.

As explained in the linked article, headless mode is useful for accessing some Java graphics features which are normally delegated to the graphics host:

After setting up headless mode and creating an instance of the headless toolkit, your application can perform the following operations:

  • Create lightweight components such as Canvas, Panel, and Swing components, except the top levels
  • Obtain information about available fonts, font metrics, and font settings
  • Set color for rendering text and graphics
  • Create and obtain images and prepare images for rendering
  • Print using java.awt.PrintJob, java.awt.print.*, and javax.print.* classes
  • Emit an audio beep

For example, in headless mode you can create and write image files:

    BufferedImage img = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    g.drawLine(80, 30, 120, 70);
    g.drawLine(80, 70, 120, 30);
    ImageIO.write(img, "png", new File("image.png"));

When run with -Djava.awt.headless=true, will produce an image file:

x

When run with -Djava.awt.headless=false (and without an X window server) will throw an exception instead:

java.awt.AWTError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable.

Note that the JVM contains heuristics that determine the value of java.awt.headless if it's not explicitly set. For example, on Linux if the DISPLAY environment variable is not set, java.awt.headless automatically becomes true.