简体   繁体   中英

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?

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.

Well I am not sure of exact numbers, but i think it'll surely increase the memory consumption a little as it has to execute the assertions.

The memory consumption can increase a lot, but that depends on what you are trying to execute within the assertion body. It might be a huge method call doing intensive work. ie the actual work you are doing to assert something. eg

assert(numberOfGrapesInFriutColumn()==5:"Number of grapes is not 5")

The method numberOfGrapesInFriutColumn() can be iterating over huge collection and doing a instance check or attribute comparison to find if the item is a grape of not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM