JIT会优化此代码吗?是否需要同步?
|
下面是一个类,其中包含拼写正确的术语的拼写错误地图。石英作业通过调用updateCache()定期更新地图。方法updatecache处理输入映射中的键和值,并将它们存储在临时映射对象中。处理完成后(在for循环之后),它将临时映射分配给本地类变量misspelledToCorrectlySpelled。
package com.test;
导入java.util.HashMap;
导入java.util.Map;
导入org.checkthread.annotations.ThreadSafe;
@ThreadSafe
公共类SpellCorrectListCacheManager {
private Map<String, String> misspelledToCorrectlySpelled =
new HashMap<String, String>(0);
/*
* invoked by a quartz job thread
*/
public void updateCache(Map<String, String> map) {
Map<String, String> tempMap = new HashMap<String, String>(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
//process key and values
String key = entry.getKey().toLowerCase();
String value = entry.getValue().toLowerCase();
tempMap.put(key, value);
}
// update local variable
this.misspelledToCorrectlySpelled = tempMap;
}
/*
* Could be invoked by *multiple* threads
*/
public Map<String, String> getMisspelledToCorrectlySpelled() {
return misspelledToCorrectlySpelled;
}
}
问题1:JIT优化会优化此代码吗?
实际代码
/*
* since tempMap is assigned to misspelledToCorrectlySpelled and not
* used anywhere else, will JIT remove tempMap as shown in the optimized
* version below?
*/
Map<String, String> tempMap = new HashMap<String, String>(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
// process key and values
String key = entry.getKey().toLowerCase();
String value = entry.getValue().toLowerCase();
tempMap.put(key, value);
}
this.misspelledToCorrectlySpelled = tempMap;
优化代码
this.misspelledToCorrectlySpelled = new HashMap<String, String>(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
//process key and values
String key = entry.getKey().toLowerCase();
String value = entry.getValue().toLowerCase();
this.misspelledToCorrectlySpelled.put(key, value);
}
问题2:假设JIT无法优化代码,方法getMisspelledToCorrectlySpelled是否应该同步?
/*
* is this assignment atomic operation?
*
* Does this needs to be synchronized?
*
* By not synchronizing, the new map may not
* be visible to other threads *immediately* -- this is
* ok since the new map will be visible after a bit of time
*
*/
this.misspelledToCorrectlySpelled = tempMap;
}
没有找到相关结果
已邀请:
2 个回复
炬卤遁蝎变
要回答有关JIT优化的问题:不,JIT不会删除临时映射的用法。
磐去裸猜饲
关键字。) 此处要求进行同步,除非“可以”看到陈旧的版本。 (这里可能不是这种情况,它可能是一个非常陈旧的版本,其中包含缓存和所有内容-因此不要打赌!)。只要“部分写入”不会发生,“引用的分配”本身就是原子的,但是不能保证在所有线程上都“立即”传播(“可见”)。 快乐的编码。