下面是一个相当常见的访问公共资源的场景,可以是顺序(单线程)方式,也可以是并发(多线程)方式。这需要最快的技术。
更具体地说(请参阅下面的示例源代码)
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() {}
}