First, look at a piece of code.
1 Public classPersonset {2 3 Private FinalSet<person> MySet =NewHashset<person>();4 5 Public synchronized voidAdd (person p) {6 Myset.add (p);7 }8 9 Public synchronized Booleancontains (person p) {Ten returnMyset.contains (p); One } A - classperson{} -}
This code is from Java concurrent programming, the book writes this code is thread-safe. As I have previously understood, I do not think it is thread-safe.
Here's my idea of the wrong idea:
If there is personset PersonA = new Personset (); Thread Threada, threadb. Threada calls the object Persona's contains () method, threadb calls the object persona the Add () method, this time is not unsafe.
--------------------------------
The problem is here, before the method synchronized keyword is actually to add an object lock to the object, that is, the current object execution of the method will have to get to the current object lock, in order to continue execution. The lock of an object, in a moment can only be a
Thread gets. That is, when thread a holds the lock of the object persona, thread B is not able to get the persona lock, then it cannot execute the synchronized method of the object persona, so the code is thread-safe.
Now that the topic has been mentioned, go ahead and pull it down.
The above code when the thread Threada executes the object persona's Add method, thread B can no longer execute the Persona Add method because it does not have a lock on the object. At this point, thread B cannot execute the Persona Add method, but it can execute Personset
The Add method of the psersonb.
--to be continued--
Java Object Locks & class Locks