View Javadoc
1   /*
2    * Copyright 2016 The Lannister Project
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package net.anyflow.lannister.message;
17  
18  import com.google.common.collect.Maps;
19  
20  import net.anyflow.lannister.cluster.ClusterDataFactory;
21  import net.anyflow.lannister.cluster.Map;
22  
23  public class MessageReferenceCounts {
24  	private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MessageReferenceCounts.class);
25  
26  	public static final MessageReferenceCounts INSTANCE = new MessageReferenceCounts();
27  
28  	private final Map<String, Integer> data; // key : message.key()
29  
30  	private MessageReferenceCounts() {
31  		this.data = ClusterDataFactory.INSTANCE.createMap("MessagesReferenceCounts_data");
32  	}
33  
34  	public java.util.Map<String, Integer> data() {
35  		java.util.Map<String, Integer> ret = Maps.newHashMap();
36  		data.keySet().stream().forEach(k -> ret.put(k, data.get(k)));
37  
38  		return ret;
39  	}
40  
41  	public void retain(String messageKey) {
42  		Integer count = data.get(messageKey);
43  		if (count == null) {
44  			count = 0;
45  		}
46  
47  		data.put(messageKey, ++count);
48  		logger.debug("RETAINed message reference [count={}, messageKey={}]", count, messageKey);
49  	}
50  
51  	public void release(String messageKey) {
52  		Integer count = data.get(messageKey);
53  		if (count == null) { return; }
54  
55  		if (count <= 0) {
56  			logger.error("Invalid Message reference Found![key={}, count={}]", messageKey, count);
57  			return;
58  		}
59  		else if (count == 1) {
60  			data.remove(messageKey);
61  			logger.debug("REMOVEed Message reference [key={}]", messageKey);
62  
63  			Message.NEXUS.remove(messageKey);
64  		}
65  		else {
66  			data.put(messageKey, --count);
67  			logger.debug("RELEASEed Message reference [key={}, count={}]", messageKey, count);
68  		}
69  	}
70  
71  	public int size() {
72  		return data.size();
73  	}
74  }