直接上代码
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class GuavaSample {
private String name = "test";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Cache<String, GuavaSample> getCache() {
return cache;
}
private static final Cache<String, GuavaSample> cache = CacheBuilder.newBuilder()
.expireAfterWrite(120L, TimeUnit.MINUTES).build();
public static void main(String[] args) {
GuavaSample obj1 = new GuavaSample();
cache.put("obj1", obj1);
// 方法一,改了实例2的属性,看是否实例1的属性是否变化
GuavaSample obj1_1 = cache.getIfPresent("obj1");
GuavaSample obj1_2 = cache.getIfPresent("obj1");
System.out.println("取出来的是否为同一个对象:" + (obj1_1 == obj1_2));
// 方法二,改了实例2的属性,看是否实例1的属性是否变化
obj1_1.setName("aaa");
obj1_2.setName("bbb");
System.out.println("取出来的是否为同一个对象:" + "bbb".equals(obj1_1.getName()));
}
}