Using a semaphore inside a nested Java 8 parallel stream action may DEADLOCK. Is this a bug?

前端 未结 3 943
名媛妹妹
名媛妹妹 2020-12-12 23:21

Consider the following situation: We are using a Java 8 parallel stream to perform a parallel forEach loop, e.g.,

IntStream.range(0,20).parallel().forEach(i         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 00:22

    Any time you are decomposing a problem into tasks, where those tasks could be blocked on other tasks, and try and execute them in a finite thread pool, you are at risk for pool-induced deadlock. See Java Concurrency in Practice 8.1.

    This is unquestionably a bug -- in your code. You're filling up the FJ pool with tasks that are going to block waiting for the results of other tasks in the same pool. Sometimes you get lucky and things manage to not deadlock (just like not all lock-ordering errors result in deadlock all the time), but fundamentally you're skating on some very thin ice here.

提交回复
热议问题