代码之家  ›  专栏  ›  技术社区  ›  PNS

最快的同步技术

  •  1
  • PNS  · 技术社区  · 14 年前

    下面是一个相当常见的访问公共资源的场景,可以是顺序(单线程)方式,也可以是并发(多线程)方式。这需要最快的技术。

    更具体地说(请参阅下面的示例源代码) Manager 类创建的一些实例 Runnable (或 Callable )类( Handler )具有公共资源(a Store 对象)。这个 经理 类实际上是子类的 execute() 方法重写以在同一线程或多个线程中顺序运行处理程序(例如,通过 ExecutorService ),取决于子类实现。

    我的问题是,什么是同步访问共享 百货商店 内部的对象 run (或 call() )每种方法 经办人 对象,特别是考虑到对于单线程访问,同步是冗余的(但必须存在,因为也有多线程 经理 子类实现)。

    例如 synchronized (this.store) {this.store.process()} 块比使用 Lock 来自的对象 java.util.concurrent ,呼叫前后 this.store.process() ?或者 synchronized 内部方法 经办人 每个商店的访问速度更快?例如,而不是调用 this.store.process() ,运行类似

    private synchronized void processStore()
    {
        this.store.process();
    }
    

    以下是(示例)源代码。

    public class Manager
    {
        public Manager()
        {
            Store store = new Store(); // Resource to be shared
            List<Handler> handlers = createHandlers(store, 10);
    
            execute(handlers);
        }
    
        List<Handler> createHandlers(Store store, int count)
        {
            List<Handler> handlers = new ArrayList<Handler>();
    
            for (int i=0; i<count; i++)
            {
                handlers.add(new Handler(store));
            }
    
            return handlers;
        }
    
        void execute(List<Handler> handlers)
        {
            // Run handlers, either sequentially or concurrently 
        }
    }
    
    public class Handler implements Runnable // or Callable
    {
        Store store; // Shared resource
    
        public Handler(Store store)
        {
            this.store = store;
        }
    
        public void run() // Would be call(), if Callable
        {
            // ...
            this.store.process(); // Synchronization needed
            // ...
            this.store.report();  // Synchronization needed
            // ...
            this.store.close();   // Synchronization needed
            // ...
        }       
    }
    
    public class Store
    {
        void process() {}
        void report()  {}
        void close()   {}
    }
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   Jeffrey    14 年前

    一般来说:CAS同步; synchronized < Lock 在速度方面。当然,这将取决于争用的程度和您的操作系统。我建议你尝试每一种,并确定哪一种最快满足你的需求。

    Java还执行 lock elision 以避免锁定仅对一个线程可见的对象。

        2
  •  1
  •   user Roman    13 年前

    据我所知,如果你的应用程序运行或将以集群模式运行,那么同步将无法工作(不同的JVM),因此锁定将是唯一的选择。

    如果公共资源是队列,则可以使用ArrayBlockingQueue,如果不是,则启动对此资源的同步访问。