不可变对象是线程安全的,但为什么呢? [英] Immutable objects are thread safe, but why?

查看:1047
本文介绍了不可变对象是线程安全的,但为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个线程通过创建其对象来创建填充不可变类的引用变量,并且在第一个线程完成之前第二次启动另一个线程并创建不可变类的另一个对象,则不会是不可变类用法是线程不安全吗?
创建一个不可变对象也表示所有字段都标记为final .....如果对新创建的实例的引用从一个线程传递到另一个线程而没有同步,则可能需要确保正确的行为
他们是否试图说另一个线程可能会将引用变量重新指向不可变类的某个其他对象,那么线程将指向不同的对象而使状态不一致?

If one thread is creating populating the reference variable of the immutable class by creating its object and at the second time the other thread kicks in before the first thread completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe? Creating a immutable object also says that all fields to marked as final as..... "it may be necessary to ensure correct behavior if a reference to a newly created instance is passed from one thread to another without synchronization" Are they trying to say that the other thread may re-point the reference variable to some other object of the immutable class and that way the threads will be pointing to different objects leaving the state inconsistent?

推荐答案


不可变对象是线程安全的,但为什么?

Immutable objects are thread safe, but why?

不可变对象是一旦构造完就不再被修改的对象。如果另外,不可变对象只有在构造完成后才能被其他线程访问,并且使用正确的同步完成,所有线程都将看到对象的相同有效状态。

An immutable object is an object that is no longer modified once it has been constructed. If in addition, the immutable object is only made accessible to other thread after it has been constructed, and this is done using proper synchronization, all threads will see the same valid state of the object.


如果一个线程正在创建通过创建其对象来填充不可变类的引用变量,并且第二次另一个线程在第一个线程完成之前启动并创建另一个对象不可变类,不可变类的使用是不是线程不安全?

If one thread is creating populating the reference variable of the immutable class by creating its object and at the second time the other thread kicks in before the first thread completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe?

否。是什么让你这么想的?对象的线程安全性完全不受您对同一类的其他对象所做的操作的影响。

No. What makes you think so? An object's thread safety is completely unaffected by what you do to other objects of the same class.


他们是否试图说出另一个线程可能会将引用变量重新指向不可变类的某个其他对象,并且线程将指向不同的对象,使状态不一致?

Are they trying to say that the other thread may re-point the reference variable to some other object of the immutable class and that way the threads will be pointing to different objects leaving the state inconsistent?

他们试图说,无论何时将某个东西从一个线程传递到另一个线程,即使它只是对不可变对象的引用,也需要同步线程。 (例如,如果通过将引用存储在对象或静态字段中将引用从一个线程传递到另一个线程,则该对象或字段由多个线程访问,并且必须是线程安全的)

They are trying to say that whenever you pass something from one thread to another, even if it is just a reference to an immutable object, you need to synchronize the threads. (For instance, if you pass the reference from one thread to another by storing it in an object or a static field, that object or field is accessed by several threads, and must be thread-safe)

这篇关于不可变对象是线程安全的,但为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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