3

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?

spongebob
  • 8,370
  • 15
  • 50
  • 83
Prasad
  • 90
  • 4
  • 5
    It is safe ... unless it extends a class that is not! – Seelenvirtuose May 05 '15 at 18:09
  • Yes, such an object would be thread safe. But of course, a class could have instance variables and have static variables and *ALSO* be thread safe. The key issue: "How is an object's 'state' managed?" Look here: [What is meant by thread-safe code?](http://stackoverflow.com/questions/261683/what-is-meant-by-thread-safe-code) – FoggyDay May 05 '15 at 18:15

1 Answers1

4

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.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 3
    Yes, but the fact that the class of an object contains no variable instance fields does not mean the object is stateless. You'll need superclasses to verify that too. – Joffrey May 05 '15 at 18:11
  • Hi Jean, Thanks for your reply!! So, if someone asks, lets say, an object is thread-safe or not? then one can look at its class and give the answer just by looking at the state. Pls correct me if I am wrong!! – Prasad May 05 '15 at 18:12
  • 1
    @Prasad you'll have to look at its superclasses too. Then, if these are stateless too, you can say it is safe. **However**, having a state does not mean it is *not* thread safe, you'll have to investigate more than that how fields are accessed. – Joffrey May 05 '15 at 18:13