1 package kotlinx.coroutines 2 3 import kotlinx.coroutines.testing.* 4 import org.junit.* 5 import org.junit.Test 6 import java.util.concurrent.atomic.* 7 import kotlin.test.* 8 9 /** 10 * Stress test for [runInterruptible]. 11 * It does not pass on JDK 1.6 on Windows: [Thread.sleep] times out without being interrupted despite the 12 * fact that thread interruption flag is set. 13 */ 14 class RunInterruptibleStressTest : TestBase() { 15 @get:Rule 16 val dispatcher = ExecutorRule(4) 17 private val repeatTimes = 1000 * stressTestMultiplier 18 19 @Test <lambda>null20 fun testStress() = runTest { 21 val enterCount = AtomicInteger(0) 22 val interruptedCount = AtomicInteger(0) 23 24 repeat(repeatTimes) { 25 val job = launch(dispatcher) { 26 try { 27 runInterruptible { 28 enterCount.incrementAndGet() 29 try { 30 Thread.sleep(10_000) 31 error("Sleep was not interrupted, Thread.isInterrupted=${Thread.currentThread().isInterrupted}") 32 } catch (e: InterruptedException) { 33 interruptedCount.incrementAndGet() 34 throw e 35 } 36 } 37 } catch (e: CancellationException) { 38 // Expected 39 } finally { 40 assertFalse(Thread.currentThread().isInterrupted, "Interrupt flag should not leak") 41 } 42 } 43 // Add dispatch delay 44 val cancelJob = launch(dispatcher) { 45 job.cancel() 46 } 47 joinAll(job, cancelJob) 48 } 49 println("Entered runInterruptible ${enterCount.get()} times") 50 assertTrue(enterCount.get() > 0) // ensure timing is Ok and we don't cancel it all prematurely 51 assertEquals(enterCount.get(), interruptedCount.get()) 52 } 53 } 54