Questions about using `assert` in Java

John Hendrikx john.hendrikx at gmail.com
Mon Jul 17 10:14:30 UTC 2023


On 17/07/2023 11:08, Alan Bateman wrote:
> 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.

I believe this can be partially alleviated by extracting the asserts to 
a method (partially as the call also increases method size).  The 
optimizer seems to be smart enough to not call the method if it does 
nothing (when ea is disabled).

--John

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


More information about the core-libs-dev mailing list