Java lock locks specific objects and javalock locks

Source: Internet
Author: User

Java lock locks specific objects and javalock locks

Since lock does not lock a specific object, how can we achieve the same effect as synchronized synchronization blocks?

Answer: assign a lock to each object needing to be locked.

Example:

List <User> users = new ArrayList <> (); // synchronize the synchronized (users. get (0) {// do something sync} // synchronize the users lock of an object. get (0 ). lock. lock (); // lock synchronization try {// do something sync} finally {users. get (0 ). lock. unlock (); // unlock} class User {/*** assigns a Lock to the user object */public lock Lock = new ReentrantLock (); public int id; public String name ;}

Efficiency Comparison (MACHINE: macOs10.12.5, i5 processor, 8 GB memory)

// Thread_count synchronized lock
// 10 1-2 ms 2-3 ms
// 100 8-12 ms 7-12 ms
// 1000 68-94 ms 64-85 ms
// 10000 642-713 ms 687-773 ms
// 100000 5500 ms 5600 ms
// 1000000 54 s 52 s
We can see that the efficiency is almost the same! Therefore, if you must use lock, use it. Otherwise, the synchronized keyword is good and easy to understand.

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.