简体   繁体   English

类的多线程

[英]Multithreading with classes

This is a bit of an interesting question but I wanted to know everyone's thoughts on this design pattern. 这是一个有趣的问题,但是我想知道每个人对这种设计模式的想法。

public class MyThreadedMap {

     private ConcurrentHashMap<Integer, Object> map;

     ...

     public class Wrapper {
          public Object get(int index){
               return map.get(index);
          }
     }
}

At this point multiple threads will have their own instance of Wrapper and would be accessing the map with wrapper.get(index). 此时,多个线程将拥有自己的Wrapper实例,并且将使用wrapper.get(index)访问该映射。

I found that the performance change from having the wrapper and not having the wrapper is just slightly better, that is the wrapper helps a little. 我发现从拥有包装器到没有包装器的性能变化稍微好一点,这就是包装器有所帮助。 When I place synchronized on the get method there is a serious performance hit. 当我将同步放置在get方法上时,会严重影响性能。

What exactly is happening here? 这里到底发生了什么? When an inner class is instantiated am I creating a copy of that get method for each instance? 当实例化一个内部类时,我是否为每个实例创建该get方法的副本? Would it be best if I just left the wrapper out since there is no real performance gain? 如果没有真正的性能提升,最好只是放弃包装器吗?

ConcurrentHashMap has fancy ways of minimizing synchronization overhead. ConcurrentHashMap具有使同步开销最小化的奇特方法。 When you synchronize the get method, it imposes normal synchronization overhead, thus the performance hit. 当您同步get方法时,它会施加正常的同步开销,从而影响性能。

If there is no other code in the Wrapper class, I would just leave it out as it doesn't appear to add anything. 如果Wrapper类中没有其他代码,则将其省略,因为它似乎未添加任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM