Questions about using `assert` in Java

Alan Bateman Alan.Bateman at oracle.com
Mon Jul 17 09:08:23 UTC 2023


On 15/07/2023 17:53, Daohan Qu wrote:
> :
>
> Although the |assert|​ keyword has been around for a long time and
> is handy for invariant checks, it does not seem to be widely used.
> For example, in the famous |j.u.c|​ packages, nearly all |assert|​
> statements are commented out [1].
>
> My questions are, should |assert|​ be heavily used in Java programs,
> especially in production code? And should we enable them in the
> production code?
>
Asserts are very useful during development or when testing, e.g. the JDK 
tests run with -esa and can periodically help catch issues when testing 
a change.

You will find places in the JDK code, esp. in performance critical code, 
where assertions are commented out. The reason is that asserts, even if 
disabled, increase the method size and can impact inlining by the 
compiler at run-time.  So while useful when debugging some issue in such 
code, they are commended out to avoid increasing the method size.

-Alan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20230717/0b7e08dc/attachment-0001.htm>


More information about the core-libs-dev mailing list