01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.management.stats;
05:
06: import java.util.ArrayList;
07: import java.util.Collection;
08: import java.util.Collections;
09: import java.util.Comparator;
10: import java.util.Iterator;
11: import java.util.SortedSet;
12: import java.util.TreeSet;
13:
14: /**
15: * Keeps track of the top <strong>N</strong> entries of all those sumbitted according to their natural order, or as
16: * defined by the passed in {@link Comparator} if the second constructor is used. <strong>The comparator should order
17: * the elements from lowest to highest, otherwise you will wind up </strong>
18: */
19: public final class TopN {
20:
21: private final SortedSet data;
22: private final int N;
23:
24: /**
25: * Creates a top {@link #N} list according to a natural ordering, if you have a custom object you will be adding use
26: * {@link #TopN(Comparator, int)} instead.
27: */
28: public TopN(final int N) {
29: this (null, N);
30: }
31:
32: /**
33: * Creates a top {@link N} list according to {@link comparator}.
34: */
35: public TopN(final Comparator comparator, final int N) {
36: data = new TreeSet(comparator != null ? new Comparator() {
37: public int compare(Object obj, Object obj1) {
38: return -comparator.compare(obj, obj1);
39: }
40: } : Collections.reverseOrder());
41: this .N = N;
42: }
43:
44: /**
45: * @param object the object added to the top N list in order, if it qualifies according to the comparator
46: */
47: public boolean evaluate(final Object object) {
48: synchronized (data) {
49: data.add(object);
50: while (data.size() > N) {
51: data.remove(data.last());
52: }
53: return data.contains(object);
54: }
55: }
56:
57: public void evaluate(final Collection objects) {
58: for (Iterator i = objects.iterator(); i.hasNext();) {
59: evaluate(i.next());
60: }
61: }
62:
63: public boolean remove(final Object object) {
64: synchronized (data) {
65: return data.remove(object);
66: }
67: }
68:
69: /**
70: * @return a read-only {@link Iterator} of the "top" {@link #N} elements, in descending order -- that is, the
71: * "biggest" one is first.
72: */
73: public Iterator iterator() {
74: synchronized (data) {
75: return Collections.unmodifiableSortedSet(data).iterator();
76: }
77: }
78:
79: public Collection getDataSnapshot() {
80: synchronized (data) {
81: return new ArrayList(data);
82: }
83: }
84:
85: }
|