Home > Net >  Thread underneath coroutineScope does not stop
Thread underneath coroutineScope does not stop

Time:04-07

i have an issue with stopping coroutine Thread. i don't have deep knowledge of Coroutines, correct me if i am wrong in any part, but i was not able to find the solution anywhere.

The issue which i am facing is that when i call coroutineScope.cancel() it does not stop the thread underneath, the coroutine is being stopped and it does not keep on functioning but the thread underneath moves to WAITING state.

The way i start my coroutine ->

        scope = CoroutineScope(
            newFixedThreadPoolContext(
                request.size,
                "Sync Proxy connection threads dispatcher"
            )
        )

In launching process, i save Job in ConcurrentHashMap ->

request.forEach {
            jobs[it] = (scope.launch {
                runConnectorProcess(it)
            })
        }

then based on some logic i call cancel ->

        jobs[request]?.let {
            it.cancel()
            jobs.remove(syncRequest)
        }

and if it was the last element canceled -> scope.cancel()

During debugging i found out in Thread Dump, that this Thread has State of WAITING Logs from VisualVM ->

"Sync Proxy connection threads dispatcher" #168 daemon prio=5 os_prio=31 tid=0x00007fa78281b800 nid=0xd42f waiting on condition [0x000000030f563000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x000000077b305878> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2044)
        at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1081)
        at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
        at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:750)

CodePudding user response:

You shouldn't expect that cancelling the CoroutineScope would also close the CoroutineDispatcher that it's referencing, because the scope doesn't own the dispatcher. The dispatcher could be used by multiple scopes and individual coroutines. It's only a parameter passed to the CoroutineScope constructor, after all. If you want to shut down your CoroutineDispatcher, you need to store it in its own property so you can call close() on it when you need to.

  • Related