com.gitee.apanlh.util.cache.local.CacheObject Maven / Gradle / Ivy
package com.gitee.apanlh.util.cache.local;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 缓存对象
*
用于Timer、LRU、LRU-K、LRU-2Q、LFU、FIFO等缓存
*
* @author Pan
*/
public class CacheObject {
/** 访问次数 */
private int count;
/** 访问次数 */
private AtomicInteger countAtomic;
/** 过期时间 */
private long expire;
/** 缓存对象 */
private V data;
/**
* 构造函数
*
* @author Pan
*/
protected CacheObject() {
super();
}
/**
* 构造函数
*
添加数据
*
默认不过期
*
* @author Pan
* @param data 数据
*/
protected CacheObject(V data) {
this(data, 0L);
}
/**
* 构造函数
*
添加数据
*
自定义过期时间
*
* @author Pan
* @param data 数据
* @param expire 过期时间
*/
protected CacheObject(V data, long expire) {
this.count = 0;
this.expire = expire;
this.data = data;
}
/**
* 获取总数
*
* @author Pan
* @return int
*/
protected int getCount() {
if (countAtomic == null) {
return this.count;
}
return countAtomic.get();
}
/**
* 设置总数
*
* @author Pan
*/
protected void setCount() {
if (countAtomic == null) {
this.count++;
return ;
}
countAtomic.incrementAndGet();
}
/**
* 获取过期时间
*
* @author Pan
* @return long
*/
protected long getExpire() {
return expire;
}
/**
* 设置过期时间
*
* @author Pan
* @param expire 过期时间
*/
protected void setExpire(long expire) {
this.expire = expire;
}
/**
* 获取数据
*
* @author Pan
* @return V
*/
protected V getData() {
return data;
}
/**
* 设置数据
*
* @author Pan
* @param data 数据
*/
protected void setData(V data) {
this.data = data;
}
/**
* 将原有计数方式改变为原子计数器
*
* @author Pan
*/
protected void enableAtomic() {
this.countAtomic = new AtomicInteger();
}
/**
* 检测是否开启原子计数器
*
* @author Pan
* @return boolean
*/
protected boolean hasEnableAtomic() {
return this.countAtomic == null;
}
@Override
public String toString() {
return "[count=" + getCount() + ", expire=" + expire + ", data=" + data + "]";
}
}