KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > logging > SimpleCounter


1 /*
2  * (c) Rob Gordon 2005
3  */

4 package org.oddjob.logging;
5
6 import java.util.HashMap JavaDoc;
7 import java.util.Map JavaDoc;
8
9 /**
10  *
11  */

12 class SimpleCounter {
13
14     private Map JavaDoc /*<String, Integer> */ counter = new HashMap JavaDoc();
15
16     public void add(Object JavaDoc key) {
17         add(key, null);
18     }
19     
20     synchronized public void add(Object JavaDoc key, Runnable JavaDoc newAction) {
21         Integer JavaDoc count = (Integer JavaDoc) counter.get(key);
22         if (count == null) {
23             count = new Integer JavaDoc(1);
24             if (newAction != null) {
25                 newAction.run();
26             }
27         } else {
28             count = new Integer JavaDoc(count.intValue() + 1);
29         }
30         counter.put(key, count);
31     }
32     
33     public void remove(Object JavaDoc key) {
34         remove(key, null);
35     }
36     
37     synchronized public void remove(Object JavaDoc key, Runnable JavaDoc emptyAction) {
38         Integer JavaDoc count = (Integer JavaDoc) counter.get(key);
39         int c = count.intValue();
40         if (c == 1) {
41             counter.remove(key);
42             if (emptyAction != null) {
43                 emptyAction.run();
44             }
45         } else {
46             count = new Integer JavaDoc(c - 1);
47         }
48     }
49     
50 }
51
Popular Tags