简介
运用共享技术实现对象复用,不会大量执行相同的方法获取对象,减少系统开销
运用场景,缓存,获得一个不会修改的对象,首先从缓存中获取,有就直接获取,没有就创建并放入缓存
Pool的使用,不管是线程池还是连接池,获得一定的连接数,放在缓存区共外部调用,不会反复创建
例子
- 缓存
实体类
public class Person {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
缓存工厂
public class DataFactory {
private Map<String, Object> map = new HashMap<>();
public Object getBySql(String sql){
//这里只是简单的进行模拟,表明一个思想
//首先从缓存中取出,不需要每次访问DB
Object o = this.map.get(sql);
if (o == null) {
System.out.println("select from db");
//模拟数据库查询
o = new Person();
((Person) o).setId("11");
((Person) o).setName("name1");
this.map.put(sql, o);
}else {
System.out.println("select from map");
}
return o;
}
}
测试
public class Main {
public static void main(String[] args) {
DataFactory factory = new DataFactory();
Object o1 = factory.getBySql("select * from person where id = 11");
System.out.println(o1);
Object o2 = factory.getBySql("select * from person where id = 11");
System.out.println(o2);
Object o3 = factory.getBySql("select * from person where id = 11");
System.out.println(o3);
// select from db
// Person{id='11', name='name1'}
// select from map
// Person{id='11', name='name1'}
// select from map
// Person{id='11', name='name1'}
}
}
- 池子
连接对象
public class Connection {
private String name;
public Connection(String name) {
this.name = name;
}
@Override
public String toString() {
return "Connection{" +
"name='" + name + '\'' +
'}';
}
}
连接池
public class DataPool {
private List<Connection> resources = new ArrayList<>();
public DataPool(int size) {
for (int i = 1; i <= size; i ++) {
//初始化资源池
this.resources.add(new Connection(i + ""));
}
}
//这里需要同步
public synchronized Connection getConnection () {
if (this.resources.size() > 0) {
Connection connection = this.resources.get(0);
this.resources.remove(connection);
return connection;
}else {
//这里也可选择扩大连接池容量
throw new RuntimeException("没有连接可以使用");
}
}
//回收没有使用的连接,避免反复的创建连接
public void release(Connection connection ){
this.resources.add(connection);
}
}
测试
public class MainDataPool {
public static void main(String[] args) {
DataPool pool = new DataPool(3);
Connection c1 = pool.getConnection();
System.out.println(c1);
Connection c2 = pool.getConnection();
System.out.println(c2);
Connection c3 = pool.getConnection();
System.out.println(c3);
try{
pool.getConnection();
}catch (Exception e){
System.out.println(e.getMessage());
}
//释放才c2
pool.release(c2);
//再次获取连接
Connection c4 = pool.getConnection();
System.out.println(c4);
// Connection{name='1'}
// Connection{name='2'}
// Connection{name='3'}
// 没有连接可以使用
// Connection{name='2'}
}
}