以下是一个相当常见的访问公共(public)资源的场景,无论是顺序(单线程)还是并发(多线程)方式,都需要最快的技术。
更具体地说(参见下面的示例源代码),Manager
类创建了一些 Runnable
(或 Callable
)类的实例(Handler
) 与公共(public)资源(Store
对象)。 Manager
类实际上是子类,它的 execute()
方法被覆盖以在同一线程或多个线程中顺序运行处理程序(例如,通过 ExecutorService
),取决于子类的实现。
我的问题是,在 run
(或 call()
) 每个 Handler
对象的方法,特别是考虑到,对于单线程访问,同步是多余的(但必须存在,因为还有多线程 Manager
子类实现)。
例如,synchronized (this.store) {this.store.process()}
block 会比使用 Lock
对象更好吗? java.util.concurrent
,调用this.store.process()
前后?或者在 Handler
中为每个商店访问单独的 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() {}
}
最佳答案
总的来说:CAS同步<synchronized
<Lock
速度方面。当然,这将取决于争用程度和您的操作系统。我建议您尝试每一种,然后确定哪种最适合您的需要。
Java 还执行 lock elision以避免锁定仅对一个线程可见的对象。
关于java - 最快的同步技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11747305/