File tree Expand file tree Collapse file tree 2 files changed +42
-4
lines changed
dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/thread Expand file tree Collapse file tree 2 files changed +42
-4
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -15,12 +15,17 @@ internal fun ThreadPoolExecutor.waitToIdle(timeoutInMs: Long): Boolean {
15
15
val startTime = System .nanoTime()
16
16
val timeoutInNs = TimeUnit .MILLISECONDS .toNanos(timeoutInMs)
17
17
val sleepDurationInMs = timeoutInMs.coerceIn(0 , MAX_SLEEP_DURATION_IN_MS )
18
+ var interrupted: Boolean
18
19
do {
19
- if (this .taskCount - this .completedTaskCount <= 0 ) {
20
+ if (isIdle() ) {
20
21
return true
21
22
}
22
- Thread .sleep (sleepDurationInMs)
23
- } while ((System .nanoTime() - startTime) < timeoutInNs)
23
+ interrupted = sleepSafe (sleepDurationInMs)
24
+ } while ((( System .nanoTime() - startTime) < timeoutInNs) && ! interrupted )
24
25
25
- return false
26
+ return isIdle()
27
+ }
28
+
29
+ internal fun ThreadPoolExecutor.isIdle (): Boolean {
30
+ return (this .taskCount - this .completedTaskCount <= 0 )
26
31
}
You can’t perform that action at this time.
0 commit comments