Using long polling to reduce number of calls.

This commit is contained in:
marcins78
2013-01-08 11:54:51 +00:00
parent c16161d919
commit 0e6e0cf0f9
5 changed files with 26 additions and 11 deletions

View File

@@ -46,6 +46,18 @@ public class ChatRoomMediator {
}
}
public boolean hasPendingMessages(String playerId) throws SubscriptionExpiredException {
_lock.readLock().lock();
try {
GatheringChatRoomListener gatheringChatRoomListener = _listeners.get(playerId);
if (gatheringChatRoomListener == null)
throw new SubscriptionExpiredException();
return gatheringChatRoomListener.hasMessages();
} finally {
_lock.readLock().unlock();
}
}
public List<ChatMessage> getPendingMessages(String playerId) throws SubscriptionExpiredException {
_lock.readLock().lock();
try {

View File

@@ -23,6 +23,10 @@ public class GatheringChatRoomListener implements ChatRoomListener {
return messages;
}
public synchronized boolean hasMessages() {
return _messages.size()>0;
}
public synchronized Date getLastConsumed() {
return _lastConsumed;
}

View File

@@ -16,6 +16,8 @@ import javax.ws.rs.core.Response;
public abstract class AbstractResource {
protected final boolean _test = System.getProperty("test") != null;
protected final long _longPollingLength = 5000;
protected final long _longPollingInterval = 200;
@Context
protected PlayerDAO _playerDao;

View File

@@ -84,17 +84,15 @@ public class ChatResource extends AbstractResource {
try {
// Use long polling
List<ChatMessage> chatMessages;
int retry = 5;
do {
chatMessages = chatRoom.getPendingMessages(resourceOwner.getName());
retry--;
long start = System.currentTimeMillis();
while (System.currentTimeMillis()<start+_longPollingLength && !chatRoom.hasPendingMessages(resourceOwner.getName())) {
try {
Thread.sleep(1000);
Thread.sleep(_longPollingInterval);
} catch (InterruptedException exp) {
}
} while (retry>0 && chatMessages.size() == 0);
}
List<ChatMessage> chatMessages = chatRoom.getPendingMessages(resourceOwner.getName());
Collection<String> usersInRoom = chatRoom.getUsersInRoom();

View File

@@ -173,11 +173,10 @@ public class GameResource extends AbstractResource {
Element update = doc.createElement("update");
// Use long polling
int retry = 5;
while (retry>0 && !gameMediator.hasAnyNewMessages(resourceOwner, channelNumber)) {
retry--;
long start = System.currentTimeMillis();
while (System.currentTimeMillis()< start+_longPollingLength && !gameMediator.hasAnyNewMessages(resourceOwner, channelNumber)) {
try {
Thread.sleep(1000);
Thread.sleep(_longPollingInterval);
} catch (InterruptedException exp) {
}