分享

IdGenerator.java

 金银宝100 2017-12-24
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)延迟加载





    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多