1 5 package com.tc.object.msg; 6 7 import java.util.HashMap ; 8 import java.util.HashSet ; 9 import java.util.Iterator ; 10 import java.util.LinkedList ; 11 import java.util.Map ; 12 import java.util.Set ; 13 14 public class MessageRecyclerImpl implements MessageRecycler { 15 16 private static final int MAX_MESSAGES_TO_HOLD = 1000; 17 18 private final LinkedList messages = new LinkedList (); 19 private final Map keys2RecycleItem = new HashMap (); 20 21 public MessageRecyclerImpl() { 22 super(); 23 } 24 25 public synchronized void addMessage(DSOMessageBase message, Set keys) { 26 if (!keys.isEmpty()) { 27 final Set lkeys = new HashSet (keys.size()); 28 RecycleItem ri = new RecycleItem(message, lkeys); 29 for (Iterator it = keys.iterator(); it.hasNext();) { 30 Object key = it.next(); 31 lkeys.add(key); 32 keys2RecycleItem.put(key, ri); 33 } 34 messages.addFirst(ri); 35 } else { 36 message.recycle(); 37 } 38 if (messages.size() > MAX_MESSAGES_TO_HOLD) { 39 RecycleItem ri = (RecycleItem) messages.removeLast(); 41 remove(ri); 42 } 43 } 44 45 private void remove(RecycleItem ri) { 46 for (Iterator it = ri.getKeys().iterator(); it.hasNext();) { 47 keys2RecycleItem.remove(it.next()); 48 } 49 } 50 51 public synchronized boolean recycle(Object key) { 52 RecycleItem ri = (RecycleItem) keys2RecycleItem.remove(key); 53 if (ri != null) { 54 Set keys = ri.getKeys(); 55 keys.remove(key); 56 if (keys.isEmpty()) { 57 messages.remove(ri); 58 DSOMessageBase message = ri.getMessage(); 59 message.recycle(); 60 return true; 61 } 62 } 63 return false; 64 } 65 66 static final class RecycleItem { 67 DSOMessageBase message; 68 Set keys; 69 70 RecycleItem(DSOMessageBase message, Set keys) { 71 this.message = message; 72 this.keys = keys; 73 } 74 75 public DSOMessageBase getMessage() { 76 return message; 77 } 78 79 public Set getKeys() { 80 return keys; 81 } 82 } 83 } 84 | Popular Tags |