Skip to content

Commit b804b68

Browse files
authored
Merge pull request #754 from DataDog/xgouchet/RUMM-1759/crash_uncaught_exception
RUMM-1759 Prevent crash on uncaught exception
2 parents 4b60fff + 75351f3 commit b804b68

File tree

2 files changed

+42
-4
lines changed

2 files changed

+42
-4
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3+
* This product includes software developed at Datadog (https://www.datadoghq.com/).
4+
* Copyright 2016-Present Datadog, Inc.
5+
*/
6+
7+
package com.datadog.android.core.internal.thread
8+
9+
import com.datadog.android.core.internal.utils.sdkLogger
10+
11+
/**
12+
* A utility method to perform a Thread.sleep() safely.
13+
* @return whether the thread was interrupted during the sleep
14+
*/
15+
internal fun sleepSafe(durationMs: Long): Boolean {
16+
try {
17+
Thread.sleep(durationMs)
18+
return false
19+
} catch (e: InterruptedException) {
20+
try {
21+
// Restore the interrupted status
22+
Thread.currentThread().interrupt()
23+
} catch (se: SecurityException) {
24+
// this should not happen
25+
sdkLogger.e("Thread was unable to set its own interrupted state", se)
26+
}
27+
return true
28+
} catch (e: IllegalArgumentException) {
29+
// This means we tried sleeping for a negative time
30+
sdkLogger.w("Thread tried to sleep for a negative amount of time", e)
31+
return false
32+
}
33+
}

dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/thread/ThreadPoolExecutorExt.kt

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,17 @@ internal fun ThreadPoolExecutor.waitToIdle(timeoutInMs: Long): Boolean {
1515
val startTime = System.nanoTime()
1616
val timeoutInNs = TimeUnit.MILLISECONDS.toNanos(timeoutInMs)
1717
val sleepDurationInMs = timeoutInMs.coerceIn(0, MAX_SLEEP_DURATION_IN_MS)
18+
var interrupted: Boolean
1819
do {
19-
if (this.taskCount - this.completedTaskCount <= 0) {
20+
if (isIdle()) {
2021
return true
2122
}
22-
Thread.sleep(sleepDurationInMs)
23-
} while ((System.nanoTime() - startTime) < timeoutInNs)
23+
interrupted = sleepSafe(sleepDurationInMs)
24+
} while (((System.nanoTime() - startTime) < timeoutInNs) && !interrupted)
2425

25-
return false
26+
return isIdle()
27+
}
28+
29+
internal fun ThreadPoolExecutor.isIdle(): Boolean {
30+
return (this.taskCount - this.completedTaskCount <= 0)
2631
}

0 commit comments

Comments
 (0)