KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > memory > UsageManagerCacheFilter


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.activemq.memory;
19
20 import java.util.concurrent.atomic.AtomicLong JavaDoc;
21
22 /**
23  * Simple CacheFilter that increases/decreases usage on a UsageManager as
24  * objects are added/removed from the Cache.
25  *
26  * @version $Revision$
27  */

28 public class UsageManagerCacheFilter extends CacheFilter {
29
30     private final AtomicLong JavaDoc totalUsage = new AtomicLong JavaDoc(0);
31     private final UsageManager um;
32
33     public UsageManagerCacheFilter(Cache next, UsageManager um) {
34         super(next);
35         this.um = um;
36     }
37
38     public Object JavaDoc put(Object JavaDoc key, Object JavaDoc value) {
39         long usage = getUsageOfAddedObject(value);
40         Object JavaDoc rc = super.put(key, value);
41         if( rc !=null ) {
42             usage -= getUsageOfRemovedObject(rc);
43         }
44         totalUsage.addAndGet(usage);
45         um.increaseUsage(usage);
46         return rc;
47     }
48     
49     public Object JavaDoc remove(Object JavaDoc key) {
50         Object JavaDoc rc = super.remove(key);
51         if( rc !=null ) {
52             long usage = getUsageOfRemovedObject(rc);
53             totalUsage.addAndGet(-usage);
54             um.decreaseUsage(usage);
55         }
56         return rc;
57     }
58     
59     
60     protected long getUsageOfAddedObject(Object JavaDoc value) {
61         return 1;
62     }
63     
64     protected long getUsageOfRemovedObject(Object JavaDoc value) {
65         return 1;
66     }
67
68     public void close() {
69         um.decreaseUsage(totalUsage.get());
70     }
71 }
72
Popular Tags