值对象中的线程安全

发布于 2024-12-17 07:15:22 字数 228 浏览 1 评论 0原文

我对同步访问java中私有实例变量的要求有点困惑。 我有一个多线程执行计划任务的应用程序。这些任务(类的实例)有一个保存值对象的实例变量。此外,这些任务具有 run 方法,通过调用保存执行逻辑的其他类来执行任务(它们反过来使用更多值对象作为处理的一部分。)

现在,在较高的级别上,看起来所有并行线程都会产生这些任务、实例变量、实现类和值对象的链。所有这些都需要线程安全吗?所有可能的类中的所有实例变量和可以并行调用的值对象?

I am a bit confused with the requirements to synchronize the access the private instance variables in java.
I have an applicaion which executes scheduled tasks multithreaded. These tasks (instances of a class) have an instance variable that holds a value object. Further, these tasks have the run methods that execute the task by calling someother classes that hold the execution logic (they in turn use more value objects as part of the processing.)

Now at a high level it looks like all the parallel threads will spawn a chain of these tasks,instance variables , implementation classes and value objects. Do all these need to be made thread safe? all instance variables in all the possible classes and value objects that can be potentially invoked in parallel?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱给你人给你 2024-12-24 07:15:22

如果多个线程要同时访问对象并且它们的状态要改变,则需要使对象线程安全。

听起来您的任务对象不是多线程的,因为不同的线程不会访问同一任务。如果这是真的,那么您就不需要使任务对象线程安全。

值对象是否可变,是否以相同的值对象实例可以同时被多个线程访问的方式共享?如果其中一个是肯定的,那么您需要使它们线程安全。

使对象线程安全的最简单方法是使其不可变。如果在构造对象后其内部状态不能改变,那么它本质上是线程安全的。如果您无法使对象不可变,那么您需要同步对其状态可能更改的任何实例变量的访问。

You need to make objects thread safe if multiple threads are going to access them at the same time and if their state is going to change.

It sounds like your task objects are not multi-threaded in that different threads won't access the same task. If that is true you wouldn't need to make your task objects thread safe.

Are the value objects mutable and are they shared in such a way that the same value object instance could be accessed by multiple threads at the same time? If either is yes then you need to make them thread safe.

The easiest way to make an object thread safe is to make it immutable. If its internal state can't change after the object is constructed then it is inherently thread safe. If you can't make your objects immutable then you need to synchronize access to any instance variables whose state could be changed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文