package cn.te.project.util
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/***
* 使用Component注解修饰的类
* 由spring管理时会为这个bean
* 默认起个名字,这个名字就是类
* 名的第一个单词的首字母小写,
* 假如希望自己指定名字,需要在
* 注解中进行配置.
*/
@Scope("singleton")//singleton表示单例
//@Scope("prototype")//prototype表示多例
@Component("idg")//给组件起个名字
//假如此对象由spring管理,则不采用延迟加载策略
@Lazy(value=false)//false表示不延迟加载
public class IdGenerator {
private Map<String,String> map=
//new HashMap<>(); //线程不安全,不锁商城
// new Hashtable<>(); // 线程安全,锁商城
new ConcurrentHashMap<>(); // 线程安全,锁换衣间
public IdGenerator() {
System.out.println("IdGenerator()");
}
/** @PostConstruct修改方法
* 在对象构建以后执行(初始化对象)*/
@PostConstruct
public void init(){
//将一个线程不安全的map转换为线程安全的map
map=Collections.synchronizedMap(map);
//从性能上讲不如ConcurrentHashMap性能高
System.out.println("init()");
}
/**@PreDestroy注解修饰的方法
* 在对象销毁之前执行(销毁对象资源)*/
@PreDestroy
public void destory(){
System.out.println("destory");
map.clear();
map=null;
}
}
//spring中如何优化对对象的使用?
//1)单例设计
//2)延迟加载
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。