方法如下:
session.setAttribute("Name",Value)
Name 随便取,value就是要放的数据
获取的时候session.getAttribute("Name)
就可以了
Java中可以使用队列来保存数据,当使用的时候,加上锁,防止其他进程访问,当不用的时候保存到数据库里面,示例如下:
package com.henryimport java.util.HashMap
import java.util.Map
import java.util.Random
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
public class CacheDataTest {
static Map<Integer,Object> dataMap=new HashMap<Integer,Object>()
static ReadWriteLock lock=new ReentrantReadWriteLock()//创建读写锁的实例
static Object getData(Integer key){
lock.readLock().lock()//读取前先上锁
Object val=null
try{
val=dataMap.get(key)
if(val == null){
// Must release read lock before acquiring write lock
lock.readLock().unlock()
lock.writeLock().lock()
try{
//可能已经由其他线程写入数据
if(val==null){
//dataMap.put(key, "")//query from db
val=queryDataFromDB(key)
}
}finally{
//Downgrade by acquiring read lock before releasing write lock
lock.readLock().lock()
// Unlock write, still hold read
lock.writeLock().unlock()
}
}
}finally{
lock.readLock().unlock()//最后一定不要忘记释放锁
}
System.out.println("get data key="+key+">val="+val)
return val
}
static Object queryDataFromDB(Integer key){
Object val=new Random().nextInt(1000)
dataMap.put(key, val)
System.out.println("write into data key="+key+">val="+val)
return val
}
public static void main(String[] args) {
for(int i=0i<10i++){
new Thread(new Runnable(){public void run() {
getData(new Random().nextInt(5))
}}).start()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)