DependingService
依赖于service
异步和动态注入的对象DependingService.setService(Object)
。如果在设置对象DependingService.doSomething()
之前service
调用,那么线程应该等待 5 秒service
才能可用。
如何进行正确有效的锁定?我的第一种方法如下所示:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class DependingService {
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Condition condition = rwLock.writeLock().newCondition();
private Object service;
// service injected dynamically by container
public void setService(final Object service) {
rwLock.writeLock().lock();
try {
this.service = service;
System.out.println("Signalling");
condition.signalAll();
} finally {
rwLock.writeLock().unlock();
}
}
public void doSomething() {
rwLock.readLock().lock();
try {
if (service == null) {
// we can't upgrade to write lock, so release read lock first
rwLock.readLock().unlock();
rwLock.writeLock().lock();
try {
if (service == null) {
System.out.println("Waiting fo 5 seconds");
condition.await(5, TimeUnit.SECONDS);
}
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
// downgrade to read lock
rwLock.readLock().lock();
rwLock.writeLock().unlock();
}
if (service == null) {
throw new RuntimeException("service is null");
}
}
// use the service
System.out.println(service.toString());
} finally {
rwLock.readLock().unlock();
}
}
}
编辑:
请注意,DependingService.setService(Object)
可能随时多次设置为 null 或任何其他对象。