Synchronization in java ForkJoinPool compute() method

南笙酒味 提交于 2020-06-01 05:07:07

问题


in Java: The Complete Reference we read:

In general, a ForkJoinTask should not use synchronized methods or synchronized blocks of code. Also, you will not normally want to have the compute( ) method use other types of synchronization, such as a semaphore

Why should I avoid synchronizing in compute()? Is it still possible in some situation to use synchronization such as semaphore or synchronized? What other method should I use from java.util.concurrent to have scallable number of threads as in ForkJoinTask and synchronization?


回答1:


You can use use synchronized methods or synchronized blocks if you are sure they would not block for a long time. As a minimum, they should not call to Object.wait() and Semaphore.aquire(), because these methods block current thread for indefinite time, and such blocking results either in memory overflow, when the thread pool tries to create new thread to replace blocked threads, or thread starvation (a kind of deadlock) where there is no available threads and all the work stops forever.

This is true for all kinds of thread pools, not only for ForkjoinPool, and for all kinds of asynchronous tasks, not only ForkJoinTask.




回答2:


From the Javadoc (emphasis mine):

A ForkJoinTask is a lightweight form of Future. The efficiency of ForkJoinTasks stems from a set of restrictions (that are only partially statically enforceable) reflecting their main use as computational tasks calculating pure functions or operating on purely isolated objects. The primary coordination mechanisms are fork(), that arranges asynchronous execution, and join(), that doesn't proceed until the task's result has been computed. Computations should ideally avoid synchronized methods or blocks, and should minimize other blocking synchronization apart from joining other tasks or using synchronizers such as Phasers that are advertised to cooperate with fork/join scheduling.



来源:https://stackoverflow.com/questions/62028011/synchronization-in-java-forkjoinpool-compute-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!