一个对象是否可以说是线程安全的?

时间:2022-04-23 11:47:27

Is it safe to say that an object is thread-safe in Java if its class contains no instance variables that can be changed and no static variables?

如果一个对象在Java中不包含可以更改的实例变量并且没有静态变量,那么它是否可以安全地用Java进行线程安全?

1 个解决方案

#1


Totally safe, as long as it does not extend a non thread-safe class.

完全安全,只要它不扩展非线程安全类。

If an object is stateless, it can safely be shared by several threads.

如果对象是无状态的,则可以安全地由多个线程共享。

That is also why it is encouraged to use immutable objects in multi-threaded environment as their state cannot be concurrently modified.

这也是为什么鼓励在多线程环境中使用不可变对象的原因,因为它们的状态不能同时修改。

#1


Totally safe, as long as it does not extend a non thread-safe class.

完全安全,只要它不扩展非线程安全类。

If an object is stateless, it can safely be shared by several threads.

如果对象是无状态的,则可以安全地由多个线程共享。

That is also why it is encouraged to use immutable objects in multi-threaded environment as their state cannot be concurrently modified.

这也是为什么鼓励在多线程环境中使用不可变对象的原因,因为它们的状态不能同时修改。