Java Object Locks & class Locks

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.