Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suppressed NPE in Json.encodeToString #2866

Closed
kosiakk opened this issue Nov 22, 2024 · 1 comment
Closed

Suppressed NPE in Json.encodeToString #2866

kosiakk opened this issue Nov 22, 2024 · 1 comment
Assignees
Labels

Comments

@kosiakk
Copy link

kosiakk commented Nov 22, 2024

Describe the bug

Java Exception breakpoint fires for NPE in JSON library ArrayPools.kt in the try-catch environment.
This has no other negative effects because the NPE is suppressed:

package kotlinx.serialization.json.internal

/*
 * Not really documented kill switch as a workaround for potential
 * (unlikely) problems with memory consumptions.
 */
private val MAX_CHARS_IN_POOL = runCatching {
    System.getProperty("kotlinx.serialization.json.pool.size").toIntOrNull()
}.getOrNull() ?: 2 * 1024 * 1024

In most cases the property is not set, it's not even documented. As result, Kotlin NullPointerException is on the main path for all JSON-write operations: getProperty("...").toIntOrNull()
I suggest we should not use the try-catch to handle the expected NPE, but instead use a null-safe call:

private val MAX_CHARS_IN_POOL = System.getProperty("kotlinx.serialization.json.pool.size")?.toIntOrNull() ?: 2 * 1024 * 1024

To Reproduce

Json { prettyPrint = true }.encodeToString("anything")

image

Expected behavior

No preventable NPE should be thrown.

Environment

  • Kotlin version: 2.0.21
  • Library version: 1.7.3
  • Kotlin platforms: JVM
@shanshin
Copy link
Contributor

Hi, thanks for the report!

Indeed, to improve readability the additional processing of the null should be added.

However, this exception does not have a significant impact on performance, because the value is initialized once, when the variable MAX_CHARS_IN_POOL is accessed for the first time.
You can verify this if you refer to the stacktrace, in which runCatching is called from the <clinit> of class ArrayPoolsKt, which is executed once when loading the class into the JVM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants