Java core knowledge point learning ---- how to create a Lock and use a Lock in a thread to design a cache system

Source: Internet
Author: User

The theoretical knowledge is boring, but these are basic skills and may be forgotten after learning. However, when used, we will find that the previous learning is very meaningful, and the learning thread is like this. 1. how to Create a lock? Lock lock = new ReentrantLock (); 2. How to Use the Lock? See the Lock document. The format is as follows: class X {private final ReentrantLock lock = new ReentrantLock ();//... public void m () {lock. lock (); // block until condition holds try {//... method body} finally {lock. unlock () }}add a lock before the method to be used, such as write operation, and then enable the lock in finally. here, we will learn from the previous java core knowledge point-use the Lock to implement data synchronization in the thread synchronization of multi-thread concurrency. The rewrite code is as follows: package com. amos. concurrent; import java. util. concurrent. locks. lock; import java. util. concurrent. loc Ks. reentrantLock;/*** @ ClassName: LockTest * @ Description: Lock learning * @ author: amosli * @ email: hi_amos@outlook.com * @ date Apr 22,201 4 1:48:36 AM */public class LockTest {public static void main (String [] args) {new LockTest (). init ();} private void init () {final OutPuter outPuter = new OutPuter (); // create a new Thread (new Runnable () {public void run () {while (true) {// 10 ms rest try {Thread. s Leep (10);} catch (InterruptedException e) {e. printStackTrace ();} outPuter. output ("hi_amos"); // output }}}). start (); new Thread (new Runnable () {public void run () {while (true) {try {Thread. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();} outPuter. output ("amosli ");}}}). start ();} static class OutPuter {// Method 1: Use the synchronized keyword // public synchronized void output (String na Me) {// int length = name. length (); // for (int I = 0; I <length; I ++) {// System. out. print (name. charAt (I); //} // System. out. println (); // Method 2: Use Lock lock = new ReentrantLock (); public void output (String name) {Lock. lock (); // lock int length = name. length (); // output name, read in bytes one by one, and output try {for (int I = 0; I <length; I ++) {System. out. print (name. charAt (I);} System. out. println ();} fin Ally {lock. unlock (); // unlock }}} 3. What is the difference between the synchronized keyword and Lock? 1 ). lock is a new feature in Java 5 and more object-oriented. it is more like a lock in life. 2 ). generally, the Lock must be manually enabled or disabled, while synchronized does not. we recommend that you use Lock first. 4. note: 1) Multiple read locks are not mutually exclusive. Read locks and write locks are mutually exclusive. Write locks and write locks are mutually exclusive. 2) To implement mutual exclusion between two threads, add the lock to the same accessed object. 3) If your code modifies data, only one person can write the data and cannot read the data at the same time, write the lock. In short, read the data with the read lock and write the data with the write lock! 5. Design a cache system. What is a cache system? Check whether the data has been cached locally. If the data has been cached, use it directly. If the data has not been cached, query the database. the following code shows the private Map <String, Object> cache = new HashMap <String, Object> (); public synchronized Object getData (String key) {Object object Object = cache. get (key); if (object = null) {object = "1323"; // actually go to queryDB ();} return object ;} this is actually a super simple cache system, the principle is: the value is saved to the cache during the first visit, the second visit, first to see whether there is a value in the cache if there is a value, instead of getting the value from the database. why is synchronized added? This is to ensure that the data is mutually exclusive and the access does not affect each other, because there is a value assignment operation on the object, which is a write operation, so it is best to add a lock. How to optimize it? Private ReadWriteLock rwl = new ReentrantReadWriteLock (); public synchronized Object getData (String key) {rwl. readLock (); // read lock Object object = cache. get (key); try {if (object = null) {rwl. readLock (). unlock (); // release the lock rwl. writeLock (). lock (); // lock write. try {object = "1323"; // actually go to queryDB ();} finally {rwl. writeLock (). unlock () ;}} finally {rwl. readLock (). unlock ();} return object;} the above Code applies the learned knowledge and locks all reads and writes to ensure mutual exclusion between threads, note that the lock should be opened in finally, regardless of whether the program is successfully executed, because if it is not unlocked, the program will produce a deadlock, we will introduce this in the next article.

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.