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