Skip to content

Commit

Permalink
Fix memory leak caused by invalid KTypeWrapper's equals method (Kotli…
Browse files Browse the repository at this point in the history
…n#2274)

* Fix KTypeWrapper equality bug to avoid memory leak

* Optimize imports of CachingTest.kt
  • Loading branch information
jooohn authored and xBaank committed Apr 20, 2023
1 parent d73f6e3 commit 836f2bd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion core/jvmMain/src/kotlinx/serialization/internal/Caching.kt
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private class KTypeWrapper(private val origin: KType) : KType {

override fun equals(other: Any?): Boolean {
if (other == null) return false
if (origin != other) return false
if (origin != (other as? KTypeWrapper)?.origin) return false

val kClassifier = classifier
if (kClassifier is KClass<*>) {
Expand Down
46 changes: 46 additions & 0 deletions core/jvmTest/src/kotlinx/serialization/CachingTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization

import kotlinx.serialization.internal.*
import kotlinx.serialization.modules.*
import org.junit.Test
import kotlin.reflect.*
import kotlin.test.*

class CachingTest {
@Test
fun testCache() {
var factoryCalled = 0

val cache = createCache {
factoryCalled += 1
it.serializerOrNull()
}

repeat(10) {
cache.get(typeOf<String>().kclass())
}

assertEquals(1, factoryCalled)
}

@Test
fun testParameterizedCache() {
var factoryCalled = 0

val cache = createParametrizedCache { clazz, types ->
factoryCalled += 1
val serializers = EmptySerializersModule().serializersForParameters(types, true)!!
clazz.parametrizedSerializerOrNull(types, serializers)
}

repeat(10) {
cache.get(typeOf<Map<*, *>>().kclass(), listOf(typeOf<String>(), typeOf<String>()))
}

assertEquals(1, factoryCalled)
}
}

0 comments on commit 836f2bd

Please sign in to comment.