Dogpile effect of java-no.06 read-write lock control cache failure illumination

Source: Internet
Author: User

package cn.guagua.mobile.common;import java.util.concurrent.locks.lock;import  Java.util.concurrent.locks.readwritelock;import java.util.concurrent.locks.reentrantreadwritelock;import  org.apache.log4j.Logger;import cn.guagua.mobile.cache.redis.Redis;/** *  read/write lock control forced read cache synchronization  *  @author  shma *  @date  2014-10-11 15:04:28 */public class  synchcachelock<t> {private static final logger logger =  Logger.getlogger (synchcachelock.class);p rivate static redis.redisclient redis1 = new  redis.redisclient ("1");p rivate readwritelock lock = null;private lock  readlock = null; //  Read Lock     private lock writelock =  null; //  write lock Public synchcachelock ()  {lock = new reentrantreadwritelock (); Readlock = lock.readlock (); writelock = lock.writelock (); System.out.println (Thread.CurrentThread (). GetName ()  +  ">>> cache lock init ...");} Public t getcache (String key, runnable task)  {T obj = null; Readlock.lock ();try {obj =  (T)  redis1.getobject (key); if (obj == null)  { System.out.println (Thread.CurrentThread (). GetName ()  +   read request   +  key +  " is null, wait query ..."); Readlock.unlock (); Writelock.lock (); try { obj =  (T)  redis1.getobject (key); if (obj == null)  {task.run ();// Enforce write Cache task System.out.println (Thread.CurrentThread (). GetName ()  +  " read request "  + key +  " end ...");obj =  (T)  redis1.getobject (key);}  catch (throwable e)  {system.out.println ("Readlock error ..."); E.printstacktrace ();}  finally {readlock.lock ();  &Nbsp;          writelock.unlock ();}} System.out.println (Thread.CurrentThread (). GetName ()  +   read request   +  key +  " data ...");  catch (throwable e)  {system.out.println ("Lock error ..."); E.printstacktrace ();}  finally {readlock.unlock ();} Return obj;}}


Dogpile effect of java-no.06 read-write lock control cache failure illumination

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.