2 Replies Latest reply: Oct 3, 2011 10:29 PM by 891906 RSS

    [SOLVED] Singleton thread safe

    891906
      If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?

      Edited by: 888903 on Oct 3, 2011 8:30 PM
        • 1. Re: Singleton thread safe
          796440
          888903 wrote:
          If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?
          First, "all instance and class variables are thread safe objects" cannot be true, because variables are not objects. Presumably you meant to say that these variables refer to threadsafe objects.

          As for your question, no, you cannot say that a given object is threadsafe just because all its member variables are. It depends on the semantics of your class, and what it needs to be atomic. For example, take the following class:
          public class Person {
            private String firstName;
            private String lastName;
          
            public String getName() {
              return firstName + " " + lastName;
            }
          
            public void updateName(String firstName, String lastName) {
              this.firstName = firstName;
              this.lastName = lastName;
            }
          }
          Here, we have a class like what you describe. (The fact your case involves a singleton is irrelevant.) My String member variables are threadsafe, but my Person class is not. If I start with "Joe Smith" and then later I call person.updateName("Fred", "Jones"), another thread could call getName() after I've updated the first but before the last, so he'd see "Fred Smith", which is incorrect. He should see only "John Smith" or "Fred Jones", not an intermediate value.
          • 2. Re: Singleton thread safe
            891906
            Thanks!