Java happend before thread start

房东的猫 提交于 2019-12-05 18:43:34

The Java Language Specification writes:

An action that starts a thread synchronizes-with the first action in the thread it starts.

If an action x synchronizes-with a following action y, then we also have hb(x, y).

If we have two actions x and y, we write hb(x, y) to indicate that x happens-before y.

However, from your description it is not clear whether that is relevant in your case, as you talk about an executor, but don't explain when that executor is created or its worker threads started.

What is relevant is the following exerpt from Executor's JavaDoc:

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

Hence your code is safe, as long as the dispatcher thread no longer accesses the list after submitting the Runnable.

According to the documentations: ExecuterService javadocs

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

This means that your concept is correct.

If there is locking or other synchronization primitives used, and you're just using a plain old ArrayList, then the two threads could see different states.

When coordinating work between two separate threads, you have to either use a thread-safe/concurrent data structure or use synchronization code to guarantee a consistent "memory snapshot" between the threads.

One of the reasons this is important is due to caching. The two threads, executing concurrently on different processors, could have cached some objects in different local registers (that are local to those processors).

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