您的位置:首页 > 运维架构 > 网站架构

使用Java设计一个 高可用、高效率的缓存系统

2014-09-04 01:09 633 查看
package concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* <pre>
* @author: bing
* @date: 2014年9月3日 下午4:30:28
* @company: ---
* @version: 1.0
* @Mail:
*
* 缓存小系统设计
* </pre>
*
*/
public class L2_CacheDemo {

public static void main(String[] args) throws InterruptedException {
final CacheData cacheData = new CacheData();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("返回值  --->" + cacheData.getData("name"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();

}

Thread.sleep(3000);
System.out.println("------------------------------------------");

for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("value --->" + cacheData.getData("name"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();

}
}
}

class CacheData {
private static Map<String, Object> cache = new HashMap<String, Object>();

/**
* 读写锁:分为读锁和写锁,读和读不互斥,读和写互斥,写和写互斥。
*/
// 只需一把锁,该锁的性质会变
private ReadWriteLock rwl = new ReentrantReadWriteLock();

/**
* <pre>
* 体会:多个线程调用同一个函数进行运算、就相当于 多个学生都在自己的作业本上做相同的题目、互不干涉、除非有共用的文具(共享数据 )、 如:共用一把尺子。
* </pre>
*/
public Object getData(String key) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + "进来了...");
rwl.readLock().lock();// 上读锁、注意:该锁的属性会改变、如:变成写锁
System.out.println(Thread.currentThread().getName() + "跨越了第一道锁...");
Object data = null;

try {
data = cache.get(key);
if (data == null) {
rwl.readLock().unlock();// 解读锁

// -----------换锁----------------------
rwl.writeLock().lock();// 上写锁
System.out.println(Thread.currentThread().getName() + "上了写锁...缓存为:" + cache);
try {
// 注意:这里的 cache.get(key)、不能换成 data、data为局部变量
if (cache.get(key) == null) {
System.out.println(Thread.currentThread().getName() + "准备写入数据...value="
+ data);
data = "小李";// 真实业务-》查询数据库
cache.put(key, data);
}
} finally {
rwl.writeLock().unlock();// 解写锁
}
// ---------------------------------

rwl.readLock().lock();// 上读锁 ,即:写完以后就赶紧换锁
System.out.println(Thread.currentThread().getName() + "换了读锁...");
}

} finally {
rwl.readLock().unlock();// 解读锁
System.out.println(Thread.currentThread().getName() + "出去了...");
}
<span style="white-space:pre">		</span>return cache.get(key);// 不能使用data 代替 cache.get(key)、因为data可能为空。	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐