KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > object > msg > MessageRecyclerImpl


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright
3  * notice. All rights reserved.
4  */

5 package com.tc.object.msg;
6
7 import java.util.HashMap JavaDoc;
8 import java.util.HashSet JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.LinkedList JavaDoc;
11 import java.util.Map JavaDoc;
12 import java.util.Set JavaDoc;
13
14 public class MessageRecyclerImpl implements MessageRecycler {
15
16   private static final int MAX_MESSAGES_TO_HOLD = 1000;
17
18   private final LinkedList JavaDoc messages = new LinkedList JavaDoc();
19   private final Map JavaDoc keys2RecycleItem = new HashMap JavaDoc();
20
21   public MessageRecyclerImpl() {
22     super();
23   }
24
25   public synchronized void addMessage(DSOMessageBase message, Set JavaDoc keys) {
26     if (!keys.isEmpty()) {
27       final Set JavaDoc lkeys = new HashSet JavaDoc(keys.size());
28       RecycleItem ri = new RecycleItem(message, lkeys);
29       for (Iterator JavaDoc it = keys.iterator(); it.hasNext();) {
30         Object JavaDoc 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       // Let GC take care of it. We dont want a OOME !
40
RecycleItem ri = (RecycleItem) messages.removeLast();
41       remove(ri);
42     }
43   }
44
45   private void remove(RecycleItem ri) {
46     for (Iterator JavaDoc it = ri.getKeys().iterator(); it.hasNext();) {
47       keys2RecycleItem.remove(it.next());
48     }
49   }
50
51   public synchronized boolean recycle(Object JavaDoc key) {
52     RecycleItem ri = (RecycleItem) keys2RecycleItem.remove(key);
53     if (ri != null) {
54       Set JavaDoc 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 JavaDoc keys;
69
70     RecycleItem(DSOMessageBase message, Set JavaDoc keys) {
71       this.message = message;
72       this.keys = keys;
73     }
74
75     public DSOMessageBase getMessage() {
76       return message;
77     }
78
79     public Set JavaDoc getKeys() {
80       return keys;
81     }
82   }
83 }
84
Popular Tags