1 18 package org.apache.activemq.transport.reliable; 19 20 import org.apache.commons.logging.Log; 21 import org.apache.commons.logging.LogFactory; 22 23 import java.io.IOException ; 24 import java.util.HashMap ; 25 import java.util.Map ; 26 27 31 public class DefaultReplayBuffer implements ReplayBuffer { 32 33 private static final Log log = LogFactory.getLog(DefaultReplayBuffer.class); 34 35 private final int size; 36 private ReplayBufferListener listener; 37 private Map map; 38 private int lowestCommandId = 1; 39 private Object lock = new Object (); 40 41 public DefaultReplayBuffer(int size) { 42 this.size = size; 43 map = createMap(size); 44 } 45 46 public void addBuffer(int commandId, Object buffer) { 47 if (log.isDebugEnabled()) { 48 log.debug("Adding command ID: " + commandId + " to replay buffer: " + this + " object: " + buffer); 49 } 50 synchronized (lock) { 51 int max = size - 1; 52 while (map.size() >= max) { 53 Object evictedBuffer = map.remove(new Integer (++lowestCommandId)); 55 onEvictedBuffer(lowestCommandId, evictedBuffer); 56 } 57 map.put(new Integer (commandId), buffer); 58 } 59 } 60 61 public void setReplayBufferListener(ReplayBufferListener bufferPoolAdapter) { 62 this.listener = bufferPoolAdapter; 63 } 64 65 public void replayMessages(int fromCommandId, int toCommandId, Replayer replayer) throws IOException { 66 if (replayer == null) { 67 throw new IllegalArgumentException ("No Replayer parameter specified"); 68 } 69 if (log.isDebugEnabled()) { 70 log.debug("Buffer: " + this + " replaying messages from: " + fromCommandId + " to: " + toCommandId); 71 } 72 for (int i = fromCommandId; i <= toCommandId; i++) { 73 Object buffer = null; 74 synchronized (lock) { 75 buffer = map.get(new Integer (i)); 76 } 77 replayer.sendBuffer(i, buffer); 78 } 79 } 80 81 protected Map createMap(int maximumSize) { 82 return new HashMap (maximumSize); 83 } 84 85 protected void onEvictedBuffer(int commandId, Object buffer) { 86 if (listener != null) { 87 listener.onBufferDiscarded(commandId, buffer); 88 } 89 } 90 } 91 | Popular Tags |