use of jp.ossc.nimbus.service.context.NoConnectServerException in project nimbus by nimbus-org.
the class SharedQueueService method lockFirst.
protected Object lockFirst(long timeout) throws SharedContextSendException, SharedContextTimeoutException {
if (isMain()) {
List keys = null;
if (context.size() != 0) {
synchronized (context) {
if (context.size() != 0) {
Iterator itr = context.keySet().iterator();
for (int i = 0; i < seekDepth && itr.hasNext(); i++) {
if (keys == null) {
keys = new ArrayList();
}
keys.add(itr.next());
}
}
}
}
if (keys == null || keys.size() == 0) {
return null;
}
for (int i = 0; i < keys.size(); i++) {
Object key = keys.get(i);
try {
if (lock(key, true, true, timeout)) {
return key;
}
} catch (SharedContextTimeoutException e) {
continue;
}
}
return null;
} else {
Object lockedKey = null;
final long start = System.currentTimeMillis();
try {
String key = getId().toString() + Thread.currentThread().getId();
Message message = serverConnection.createMessage(subject, key);
Set receiveClients = serverConnection.getReceiveClientIds(message);
if (receiveClients.size() != 0) {
message.setObject(new SharedQueueEvent(SharedQueueEvent.EVENT_LOCK_FIRST, null, new Object[] { new Long(Thread.currentThread().getId()), new Long(timeout) }));
Message[] responses = serverConnection.request(message, isClient ? clientSubject : subject, key, 1, timeout);
Object ret = responses[0].getObject();
responses[0].recycle();
if (ret instanceof Throwable) {
throw new SharedContextSendException((Throwable) ret);
} else {
lockedKey = ret;
}
} else {
throw new NoConnectServerException("Main server is not found.");
}
} catch (MessageException e) {
throw new SharedContextSendException(e);
} catch (MessageSendException e) {
throw new SharedContextSendException(e);
} catch (RequestTimeoutException e) {
final boolean isNoTimeout = timeout <= 0;
timeout = isNoTimeout ? timeout : timeout - (System.currentTimeMillis() - start);
if (!isNoTimeout && timeout <= 0) {
throw new SharedContextTimeoutException("timeout=" + timeout + ", processTime=" + (System.currentTimeMillis() - start), e);
} else {
return lockFirst(timeout);
}
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
}
if (lockedKey != null) {
Lock lock = null;
synchronized (keyLockMap) {
lock = (Lock) keyLockMap.get(lockedKey);
if (lock == null) {
lock = new Lock(lockedKey);
keyLockMap.put(lockedKey, lock);
}
}
final boolean isNoTimeout = timeout <= 0;
timeout = isNoTimeout ? timeout : timeout - (System.currentTimeMillis() - start);
if (!isNoTimeout && timeout <= 0) {
unlock(lockedKey);
throw new SharedContextTimeoutException("timeout=" + timeout + ", processTime=" + (System.currentTimeMillis() - start));
} else if (!lock.acquire(getId(), true, timeout)) {
unlock(lockedKey);
return null;
}
}
return lockedKey;
}
}
Aggregations