Search code examples
javaassertionsjvm-arguments

Does enabling Java assertions increase memory consumption significantly?


I've been working on a Java program that reads large CSV files, processes the contents, and submits it to a Solr server depending on certain criteria. The code has been working fine for some time with an initial data set. But as it has not been tested extensively, so I have enabled assertions with the -ea flag when running it on another data set of about quadruple size recently (~2.2MB vs ~640KB).

I run into an OutOfMemoryException with the new dataset even after doubling max heap size to 8G (-Xmx8g). My current code is not particularly memory-efficient, so I am probably able to fix the issue in the code.

However, when reading upon Java assertions, I notice that memory consumption is apparently never discussed in this context. My question is thus: does enabling assertions in the JVM increase memory consumption by a measurable amount? Should this be taken into account when testing/debugging code and when optimizing for memory-efficiency?


Solution

  • Well, an assertion such as:

    assert condition : "error message";
    

    Gets compiled into a simple check-and-throw statement:

    if(!$assertionsDisabled && !condition)
        throw new AssertionError("error message");
    

    Where $assertionsDisabled is a constant field generated by the compiler for each class where assertions are present:

    static final boolean $assertionsDisabled = !ThisClass.class.desiredAssertionStatus();
    

    So I would say that the overhead is quite small, especially memory-wise. I would take a profiler and measure the memory consumption of the given application. You'll probably find out that there are memory issues elsewhere.