基于项目学习使用
测试用例
public class DomeServiceImpl implements IDomeService {
private static Logger logger = LoggerFactory.getLogger(DomeServiceImpl.class);
public void test01() {
synchronized (this) {
logger.info("测试同步代码块");
}
logger.info("============================");
synchronized (DomeServiceImpl.class) {
logger.info("测试同步代码块");
}
}
public synchronized void test02() {
logger.info("测试同步方法");
}
public static synchronized void test03() {
logger.info("测试同步静态方法");
}
}
切换到该类的目录下,执行javac DomeServiceImpl.java进行编译,然后再切换到对应的class文件目录下,执行javap -c -s -v -l DomeServiceImpl.class
图中标红处就是加锁的标识
monitorenter:表示开始加锁的位置
monitorexit:表示结束加锁的位置
ACC_SYNCHRONIZED:表示加锁的标识,代表当前方法是一个同步方法
项目中使用
boolean supProcessHotProblemLoaded = false;
private void loadSupProcessHotProblems() {
if (supProcessHotProblemLoaded) return;
synchronized (this) {
if (supProcessHotProblemLoaded) return;
supProcessHotProblemLoaded = true;
long t = System.currentTimeMillis();
List<SupRecordProcessHotProblemDs> prcHotProblems = DataSetUtils.loadDataSetsBy(bizDbService, SupRecordProcessHotProblemDs.class,
"process_id", this.getEffectIdsByDsClass(SupRecordProcessDs.class));
for (SupRecordProcessHotProblemDs data : prcHotProblems) {
SupRecordProcessDs prc = this.getDsDataByDsClassAndDsPkVal(SupRecordProcessDs.class, data.getProcess_id());
prc.addHotProblem(data);
}
logger.info("加载 热点问题 耗时:" + (System.currentTimeMillis() - t) + "ms");
}
}
//分发日志配置
private List<LogDispenseConfig> cfgs=null;
public synchronized List<LogDispenseConfig> findLogDispenseConfigs(Boolean priority){
if(this.cfgs==null) {
this.cfgs=this.createHQLQueryByParams(LogDispenseConfig.class,
" from "+LogDispenseConfig.class.getName()+" where valid=1")
.list();
}
if(this.cfgs==null) this.cfgs=new ArrayList<>();
List<LogDispenseConfig> cfgs=new ArrayList<LogDispenseConfig>();
for (LogDispenseConfig cfg : this.cfgs) {
if(priority!=null) {
if(priority&&!cfg.isOnlyPriority()) {
continue;
}
else if(!priority&&cfg.isOnlyPriority()) {
continue;
}
}
cfgs.add(cfg);
}
return cfgs;
}