以下是以顺序(单线程)或并发(多线程)方式访问公共资源的一个相当常见的场景,需要最快的技术。
更具体地说(参见下面的示例源代码),Manager类创建具有公共资源( Store对象)的Runnable (或Callable)类(Handler)的一些实例。Manager类实际上是子类,它的execute()方法被覆盖,以在同一线程或多个线程(例如,通过ExecutorService)中顺序运行处理程序,具体取决于子类实现。
我的问题是,在每个Store对象的run (或call())方法中同步对共享Handler对象的访问的最快(开销较小)方法是什么,特别是考虑到,对于单线程访问,这种同步是多余的(但必须存在,因为还有多线程Manager子类实现)。
例如,在调用java.util.concurrent之前和之后,synchronized (this.store) {this.store.process()}块会比使用来自java.util.concurrent的Lock对象更好吗?或者,在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() {}
}发布于 2012-08-01 03:16:48
一般而言: CAS同步< synchronized < Lock在速度方面。当然,这将取决于争用的程度和您的操作系统。我建议您尝试每一个,并确定哪一个最快,以满足您的需求。
Java还执行lock elision,以避免锁定仅对一个线程可见的对象。
发布于 2012-11-12 20:50:37
据我所知,如果您的应用程序运行或将运行在集群模式,那么同步将不会工作(不同的JVM),因此锁定将是唯一的选择。
如果公共资源是队列,那么您可以使用ArrayBlockingQueue,如果不是,则开始对此资源进行同步访问。
https://stackoverflow.com/questions/11747305
复制相似问题