是否直接使用Object.wait和Object.notify代码气味? [英] Is using Object.wait and Object.notify directly a code smell?

查看:177
本文介绍了是否直接使用Object.wait和Object.notify代码气味?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是有争议的,但我只是意识到我很少使用wait和notify直接。相反,我使用 <$ c中的一些较高级别的结构$ c> java.util.concurrent 包。有没有使用wait和notify是唯一的解决方案,或者应该只在构建更高级别的结构时使用它们?

This might be controversial, but I just realized I very seldom use wait and notify directly. Instead, I use some higher-level construct from the java.util.concurrent package. Are there use cases where wait and notify are the only solution or should they only be used when building higher-level constructs?

推荐答案


有没有使用wait和notify是唯一的解决方案,或者应该只在构建更高级别的结构时使用它们吗?

Are there use cases where wait and notify are the only solution or should they only be used when building higher-level constructs?

它们只应在构建更高级别的构造时使用。如果你有一种情况,现有的更高级别的结构不能解决你的问题,你不想恢复等待/通知;你想设计一个更高层次的结构来解决你的问题。您可以使用wait / notify实现它。

They should only be used when building higher-level constructs. If you have a case where the existing higher-level constructs don't solve your problem, you don't want to revert to wait/notify; you want to design a higher-level construct that solves your problem. You may implement it with wait/notify.

例如,我曾经遇到过一个问题,需要并发执行具有层次依赖性的任务集合,连接(和)和析取(或)的组合。即,存在一个任务的条件是任务A完成并且任务B完成的情况,其中是任务A完成或任务B完成的情况,以及这些的各种组合(例如,任务A是完成,任务B或任务C完成)。

For example, I once had a problem that required concurrent execution of a collection of tasks with hierarchical dependencies, where the dependency conditions involved a combination of conjunction ("and") and disjunction ("or"). I.e., there were cases where one task's condition was "Task A is done and Task B is done," cases where it was "Task A is done or Task B is done," and various combinations of these (e.g., "Task A is done, and either Task B or Task C is done").

所以我写了一个小实用程序库,为客户提供一个接口,条件,一旦满足其前提条件,将这些任务提交给 Executor ,并监视任务完成以启动新合格的任务。其中一些是使用 java.util.concurrent (主要是 Executor Semaphore ),但其他部分涉及使用wait / notify(coordinator线程通知任务完成与wait / notify)。

So I wrote a small utility library that provided an interface for clients to submit collections of tasks annotated with their conditions, submitted these tasks to an Executor as soon as their preconditions were met, and monitored task completion to kick off newly eligible tasks. Some of that was implemented using java.util.concurrent (mainly Executor and Semaphore), but other parts involved using wait/notify (the "coordinator" thread is notified of task completion with wait/notify).

结束了更容易理解和疑难解答,后来我们发现同一任务协调器库的其他用途。

So the code ended up much easier to understand and troubleshoot, and later we found other uses for the same task coordinator library.

这篇关于是否直接使用Object.wait和Object.notify代码气味?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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