问题描述
如果我仅使用不可变数据类型,那么我的Java程序将是线程安全的吗?
Is it true that if I only use immutable data type, my Java program would be thread safe?
还有其他因素会影响线程安全吗?
Any other factors will affect the thread safety?
****如果能提供一个例子,将不胜感激.谢谢!****
****Would appreciate if can provide an example. Thanks!****
推荐答案
线程安全是关于保护共享数据的,不可变对象是只读的,因此受到保护.除了创建它们之外,创建对象是线程安全的.
Thread safety is about protecting shared data and immutable objects are protected as they are read only. Well apart from when you create them but creating a object is thread safe.
值得一提的是,设计一个仅使用不可变对象来实现线程安全的大型应用程序将很困难.
It's worth saying that designing a large application that ONLY uses immutable objects to achieve thread safety would be difficult.
这是一个复杂的主题,我建议您阅读实践中的Java并发这是一个很好的起点.
It's a complicated subject and I would recommend you reading Java Concurrency in Practicewhich is a very good place to start.
这篇关于仅使用不可变数据类型会使Java程序线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!