Understanding parallel exists and find

Deadly 提交于 2019-12-01 03:33:08

Why doesn't it just send out the message to the other threads to abort mission as soon as the first result is found?

Because that is not possible. JAVA DOES NOT LET YOU DO THAT. Or, rather, it does, but it is deprecated.

See description of (deprecated) Thread.stop():

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

In other words, because multithreaded code with locks are inherently broken, they deprecated a perfectly fine method that can be happily used with threads that do not share mutable state and, therefore, need not lock data structures.

I understand the desire, because I thought myself it would be nice, to have such a behaviour - from the intention to use fast exiting code, it looks reasonable to expect it, but of course, how should it be implemented?

In shortcutting expressions, the next call isn't started, if the result is found - that is easy.

But how do you run behind an offired task, and catch it again to stop it? You would need to know which of them has already finished, and might step into a race condition, because while testing, whether it is still running, it might return 'true', but finish immeadeately afterwards.

The function which is called inside exists could start new Threads itself - how should they be stopped from outside in a general way? By providing an optional stop execution-method as second parameter perhaps?

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