Java 关于同步

Java 关于同步,java,Java,我对调用方法的缓存结果的同步表示怀疑, 伪代码如下 Cache cache = cacheMap.get("cacheKey"); // get implemented synchronization if(cache!=null){ return cache; } result = invokeLongTimeMethod(); //this method is thread-safe map.put("cacheKey",result); // put implemented sy

我对调用方法的缓存结果的同步表示怀疑, 伪代码如下

Cache cache = cacheMap.get("cacheKey"); // get implemented synchronization
if(cache!=null){
   return cache;
}
result = invokeLongTimeMethod();  //this method is thread-safe
map.put("cacheKey",result);  // put implemented synchronzization as well.
sychronized(this){
   result=invokeLongTimeMethod(); //notice: this method can be invoked more than one time 
}
invokeLongTimeMethod()是否需要使用关键字进行包装(同步化)?如下

Cache cache = cacheMap.get("cacheKey"); // get implemented synchronization
if(cache!=null){
   return cache;
}
result = invokeLongTimeMethod();  //this method is thread-safe
map.put("cacheKey",result);  // put implemented synchronzization as well.
sychronized(this){
   result=invokeLongTimeMethod(); //notice: this method can be invoked more than one time 
}

我认为不添加同步代码似乎性能更好。

这取决于并行调用
invokeLongTimeMethod
两次有多糟糕

事实上,如果不同步,两个及时关闭的线程都可能在找不到缓存项后很长一段时间内开始计算该值。但是,如果并行调用
invokeLongTimeMethod
是安全的,那么两个返回值对于任务来说都是完全相同的,并且调用没有重要的副作用,这似乎只是稍微降低了效率。两个计算值中的一个将被缓存以备将来使用


但是,如果上述条件不成立,则需要同步以挂起一个线程,而另一个线程已经在计算缓存的缺失值。

请提出一个明确、具体的问题。