Java ForkJoinPool的compute()方法中的同步 [英] Synchronization in java ForkJoinPool compute() method

查看:165
本文介绍了Java ForkJoinPool的compute()方法中的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中:我们阅读的完整参考资料:

in Java: The Complete Reference we read:

通常,ForkJoinTask不应使用同步方法或 同步代码块.另外,您通常不希望拥有 compute()方法使用其他类型的同步,例如 信号量

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

为什么要避免在compute()中进行同步? 在某些情况下是否仍可以使用同步,例如信号量或已同步? 我应该从java.util.concurrent使用什么其他方法来拥有如ForkJoinTask和同步中可调用的线程数?

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?

推荐答案

如果确定它们不会长时间阻塞,则可以使用同步方法或同步块.至少,它们不应调用Object.wait()Semaphore.aquire(),因为这些方法会无限期地阻塞当前线程,并且这种阻塞会导致内存溢出(当线程池尝试创建新线程来替换阻塞的线程时),或线程匮乏(一种死锁),那里没有可用的线程,所有工作将永远停止.

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.

对于所有类型的线程池,不仅对于ForkjoinPool,而且对于所有异步任务,不仅对于ForkJoinTask,都是如此.

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

这篇关于Java ForkJoinPool的compute()方法中的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆