Skip to content

Commit e670f62

Browse files
Workaround transient issue in JobCancellationException (#4291)
Co-authored-by: Vsevolod Tolstopyatov <[email protected]>
1 parent 3c1f6d5 commit e670f62

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

kotlinx-coroutines-core/jvm/src/Exceptions.kt

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ internal actual class JobCancellationException public actual constructor(
6161
override fun equals(other: Any?): Boolean =
6262
other === this ||
6363
other is JobCancellationException && other.message == message && other.job == job && other.cause == cause
64-
override fun hashCode(): Int =
65-
(message!!.hashCode() * 31 + job.hashCode()) * 31 + (cause?.hashCode() ?: 0)
64+
65+
override fun hashCode(): Int {
66+
// since job is transient it is indeed nullable after deserialization
67+
@Suppress("UNNECESSARY_SAFE_CALL")
68+
return (message!!.hashCode() * 31 + (job?.hashCode() ?: 0)) * 31 + (cause?.hashCode() ?: 0)
69+
}
6670
}

kotlinx-coroutines-core/jvm/test/JobCancellationExceptionSerializerTest.kt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,30 @@ class JobCancellationExceptionSerializerTest : TestBase() {
3636
finish(4)
3737
}
3838
}
39+
40+
@Test
41+
fun testHashCodeAfterDeserialization() = runTest {
42+
try {
43+
coroutineScope {
44+
expect(1)
45+
throw JobCancellationException(
46+
message = "Job Cancelled",
47+
job = Job(),
48+
cause = null,
49+
)
50+
}
51+
} catch (e: Throwable) {
52+
finish(2)
53+
val outputStream = ByteArrayOutputStream()
54+
ObjectOutputStream(outputStream).use {
55+
it.writeObject(e)
56+
}
57+
val deserializedException =
58+
ObjectInputStream(outputStream.toByteArray().inputStream()).use {
59+
it.readObject() as JobCancellationException
60+
}
61+
// verify hashCode does not fail even though Job is transient
62+
assert(deserializedException.hashCode() != 0)
63+
}
64+
}
3965
}

0 commit comments

Comments
 (0)