0

enter image description here

Had there been a

 public synchronized void deletePerson(Person p)
      { mySet.remove();}

then too it would remain threadsafe?

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
prvn
  • 684
  • 6
  • 21
  • `@ThreadSafe` is not part of the Java API. It must come with a third party library and you should look into the documentation for the same. You may look into this question: http://stackoverflow.com/questions/11362298/guardedby-threadsafe-notthreadsafe – dotvav Sep 16 '15 at 09:11

2 Answers2

5

This class is threadsafe because there is only one mutable field in it (mySet) , it is private and all accesses to it are synchronized.

Yes, public synchronized void deletePerson(Person p) { mySet.delete();} would still keep this class thread-safe.

Also, note that the reference to mySet is not escaping from this class. Which is also important.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • suppose there are two threads thread1 and thread2. thread1 gets the lock on mySet object ,adds Person P1 through addPerson() method releases the lock. Due to some unlucky timing it might happen that thread2 gets the lock on mySet object, removes the Person P1 and releases the lock. Then thread1 will then get a false value from containsPerson(). – prvn Sep 16 '15 at 09:19
  • @prvn - No. it can't happen. *Synchronization* enforces a *happens-before* relationship. So, it is guaranteed that before a lock is acquired, a thread sees all the changes made by other threads – TheLostMind Sep 16 '15 at 09:37
  • yes, exactly thread2 sees that thread1 added P1 , it then removes P1, thread1 sees the changes made and therefore when it calls containsPerson() , it gets a false value. But this scenario is not we call as threadsafe. If a thread adds a info it should retrieve the same info that it added. But here its not happening. – prvn Sep 16 '15 at 09:48
  • 1
    @prvn - No. *thread-safe* means - get the *latest* state and NOT - *what thread changed* state – TheLostMind Sep 16 '15 at 09:50
0

Since mySet is private and not exposed outside the class through a getMySet method, you can access to the state of the object only with the methods addPerson, containsPerson and deletePerson.

Since these 3 methods are synchronized, only one of them can access to the instance of the class (and change its state) at any given time, so the class is Thread Safe.

alessiop86
  • 1,285
  • 2
  • 19
  • 38