You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by rm...@apache.org on 2013/07/29 08:20:58 UTC
svn commit: r1507950 [2/8] - in /commons/sandbox/monitoring/trunk: ./ aop/
aop/src/main/java/org/apache/commons/monitoring/aop/
aop/src/main/java/org/apache/commons/monitoring/instrumentation/
aop/src/main/resources/ aop/src/test/java/org/ aop/src/test...
Copied: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Counter.java (from r1506987, commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Metric.java)
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Counter.java?p2=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Counter.java&p1=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Metric.java&r1=1506987&r2=1507950&rev=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Metric.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Counter.java Mon Jul 29 06:20:54 2013
@@ -15,26 +15,19 @@
* limitations under the License.
*/
-package org.apache.commons.monitoring;
+package org.apache.commons.monitoring.counter;
-import java.util.EventListener;
+import org.apache.commons.monitoring.Role;
+import org.apache.commons.monitoring.Visitable;
+import org.apache.commons.monitoring.monitors.Monitor;
/**
* A <code>Metric</code> is a numerical indicator of some monitored application state with support for simple
* statistics.
- *
+ *
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public interface Metric
- extends Visitable
-{
- public enum Type
- {
- COUNTER, GAUGE
- };
-
- Type getType();
-
+public interface Counter extends Visitable {
/**
* reset the Metric
*/
@@ -42,29 +35,27 @@ public interface Metric
/**
* Add value to the metric. For Counters, the value is expected to be always positive.
- * <p>
+ * <p/>
* The delta MUST use the metric unit ({@link #getUnit()})
- *
+ *
* @param delta value to be added
*/
- void add( double delta );
+ void add(double delta);
/**
* Add value to the metric with the specified Unit. For Counters, the value is expected to be always positive.
- *
+ *
* @param delta value to be added
- * @param unit the unit used for delta, MUST be compatible with the metric unit ({@link #getUnit()})
+ * @param unit the unit used for delta, MUST be compatible with the metric unit ({@link #getUnit()})
*/
- void add( double delta, Unit unit );
+ void add(double delta, Unit unit);
/**
* Set the monitor this Metric is attached to
- *
+ *
* @param monitor
- * @throws IllegalStateException if the Metric is allready attached to a monitor
*/
- void setMonitor( Monitor monitor )
- throws IllegalStateException;
+ void setMonitor(Monitor monitor);
/**
* @return the monitor this Metric is attached to
@@ -81,41 +72,6 @@ public interface Metric
*/
Unit getUnit();
- /**
- * Listener for Metric events
- */
- public static interface Listener
- extends EventListener
- {
- /**
- * Value has changed on Metric.
- * <p>
- * Note that the value parameter has not the same content depending on Metric variant: for a @ Counter} it is
- * the delta added to the counter for a @ Gauge} it is the new value of the gauge after beeing updated.
- *
- * @param metric
- * @param value
- */
- void onValueChanged( Observable metric, double value );
- }
-
- /**
- * A metric that support the Observer pattern.
- */
- public interface Observable
- extends Metric
- {
- /**
- * @param listener listener to get registered
- */
- void addListener( Listener listener );
-
- /**
- * @param listener listener to get removed
- */
- void removeListener( Listener listener );
- }
-
// --- Statistical indicators --------------------------------------------
double getMax();
Added: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/DefaultCounter.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/DefaultCounter.java?rev=1507950&view=auto
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/DefaultCounter.java (added)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/DefaultCounter.java Mon Jul 29 06:20:54 2013
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.counter;
+
+import org.apache.commons.math.stat.descriptive.SummaryStatistics;
+import org.apache.commons.monitoring.Role;
+import org.apache.commons.monitoring.Visitor;
+import org.apache.commons.monitoring.configuration.Configuration;
+import org.apache.commons.monitoring.counter.queuemanager.MetricQueueManager;
+import org.apache.commons.monitoring.monitors.Monitor;
+
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class DefaultCounter implements Counter {
+ private static final MetricQueueManager QUEUE_MANAGER = Configuration.newInstance(MetricQueueManager.class);
+
+ protected Monitor monitor;
+ protected SummaryStatistics statistics;
+ protected Role role;
+ protected Unit unit;
+ protected Lock lock = new ReentrantLock();
+
+ public DefaultCounter(final Role role) {
+ this.role = role;
+ this.unit = role.getUnit();
+ this.statistics = new SummaryStatistics();
+ }
+
+ public void addInternal(final double delta) { // should be called from a thread safe environment
+ statistics.addValue(delta);
+ }
+
+ @Override
+ public void reset() {
+ statistics.clear();
+ }
+
+ @Override
+ public void add(final double delta) { // sensitive method which need to be thread safe, default implementation relies on disruptor
+ QUEUE_MANAGER.add(this, delta);
+ }
+
+ @Override
+ public void add(final double delta, final Unit deltaUnit) {
+ add(unit.convert(delta, deltaUnit));
+ }
+
+ @Override
+ public void setMonitor(final Monitor monitor) {
+ this.monitor = monitor;
+ }
+
+ @Override
+ public Monitor getMonitor() {
+ return monitor;
+ }
+
+ @Override
+ public Role getRole() {
+ return role;
+ }
+
+ @Override
+ public Unit getUnit() {
+ return unit;
+ }
+
+ @Override
+ public double getMax() {
+ return statistics.getMax();
+ }
+
+ @Override
+ public double getMin() {
+ return statistics.getMin();
+ }
+
+ @Override
+ public double getSum() {
+ return statistics.getSum();
+ }
+
+ @Override
+ public double getStandardDeviation() {
+ return statistics.getStandardDeviation();
+ }
+
+ @Override
+ public double getVariance() {
+ return statistics.getVariance();
+ }
+
+ @Override
+ public double getMean() {
+ return statistics.getMean();
+ }
+
+ @Override
+ public double getGeometricMean() {
+ return statistics.getGeometricMean();
+ }
+
+ @Override
+ public double getSumOfLogs() {
+ return statistics.getSumOfLogs();
+ }
+
+ @Override
+ public double getSumOfSquares() {
+ return statistics.getSumOfLogs();
+ }
+
+ @Override
+ public long getHits() {
+ return statistics.getN();
+ }
+
+ @Override
+ public void accept(final Visitor visitor) {
+ visitor.visit(this);
+ }
+
+ public Lock getLock() {
+ return lock;
+ }
+}
Copied: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Unit.java (from r1506987, commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Unit.java)
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Unit.java?p2=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Unit.java&p1=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Unit.java&r1=1506987&r2=1507950&rev=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Unit.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/Unit.java Mon Jul 29 06:20:54 2013
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.commons.monitoring;
+package org.apache.commons.monitoring.counter;
import java.util.ArrayList;
import java.util.Collections;
@@ -31,77 +31,77 @@ import java.util.concurrent.CopyOnWriteA
* that represent the same data type, but with a scale factor.
* A primary Unit is created with the {@link Unit#Unit(String)} constructor.
* A derived Unit is created with the {@link Unit#Unit(String, Unit, long)} constructor.
- * <p>
- * A primary Unit maintains a Map of it's derived units. {@ Unit#getDerived()} can be
- * used to retrieve the complete list, and {@ Unit#getDerived(String)} to retrieve a
+ * <p/>
+ * A primary Unit maintains a Map of it's derived units. {@see Unit#getDerived()} can be
+ * used to retrieve the complete list, and {@see Unit#getDerived(String)} to retrieve a
* derived unit by it's name.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public class Unit implements Comparable<Unit>
-{
- private static final Map<String, Unit> UNITS = new ConcurrentHashMap<String,Unit>();
+public class Unit implements Comparable<Unit> {
+ private static final Map<String, Unit> UNITS = new ConcurrentHashMap<String, Unit>();
- /** Time based units */
+ /**
+ * Time based units
+ */
public static class Time
- extends Unit
- {
- public static final Unit NANOSECOND = new Unit( "ns" );
- public static final Unit MICROSECOND = new Unit( "µs", NANOSECOND, 1000 );
- public static final Unit MILLISECOND = new Unit( "ms", MICROSECOND, 1000 );
- public static final Unit SECOND = new Unit( "s", MILLISECOND, 1000 );
- public static final Unit MINUTE = new Unit( "min", SECOND, 60 );
- public static final Unit HOUR = new Unit( "h", MINUTE, 60 );
- public static final Unit DAY = new Unit( "day", HOUR, 24 );
+ extends Unit {
+ public static final Unit NANOSECOND = new Unit("ns");
+ public static final Unit MICROSECOND = new Unit("µs", NANOSECOND, 1000);
+ public static final Unit MILLISECOND = new Unit("ms", MICROSECOND, 1000);
+ public static final Unit SECOND = new Unit("s", MILLISECOND, 1000);
+ public static final Unit MINUTE = new Unit("min", SECOND, 60);
+ public static final Unit HOUR = new Unit("h", MINUTE, 60);
+ public static final Unit DAY = new Unit("day", HOUR, 24);
- public Time( String name )
- {
- super( name );
+ public Time(String name) {
+ super(name);
}
- public Time( String name, Unit derived, long scale )
- {
- super( name, derived, scale );
+ public Time(String name, Unit derived, long scale) {
+ super(name, derived, scale);
}
}
- /** Binary data units */
+ /**
+ * Binary data units
+ */
public static class Binary
- extends Unit
- {
+ extends Unit {
- public static final Unit BYTE = new Unit( "b" );
+ public static final Unit BYTE = new Unit("b");
- public static final Unit KBYTE = new Unit( "Kb", BYTE, 1024 );
+ public static final Unit KBYTE = new Unit("Kb", BYTE, 1024);
- public static final Unit MBYTE = new Unit( "Mb", KBYTE, 1024 );
+ public static final Unit MBYTE = new Unit("Mb", KBYTE, 1024);
- public static final Unit GBYTE = new Unit( "Gb", MBYTE, 1024 );
+ public static final Unit GBYTE = new Unit("Gb", MBYTE, 1024);
- public Binary( String name )
- {
- super( name );
+ public Binary(String name) {
+ super(name);
}
- public Binary( String name, Unit derived, long scale )
- {
- super( name, derived, scale );
+ public Binary(String name, Unit derived, long scale) {
+ super(name, derived, scale);
}
}
- /** unit for basic item counters & gauges */
+
+ /**
+ * unit for basic item counters & gauges
+ */
// "BILLION" does not have same signification depending on country (10^12 or 10^9).
// We use International system of unit names to avoid confusion
// @see http://en.wikipedia.org/wiki/SI
- public static final Unit UNARY = new Unit( "" );
- public static final Unit DECA = new Unit( "*10", UNARY, 10 );
- public static final Unit HECTO = new Unit( "*100", DECA, 10 );
- public static final Unit KILO = new Unit( "*1000", HECTO, 10 );
- public static final Unit MEGA = new Unit( "*10^6", KILO, 1000 );
- public static final Unit GIGA = new Unit( "*10^9", MEGA, 1000 );
- public static final Unit TERA = new Unit( "*10^12", GIGA, 1000 );
+ public static final Unit UNARY = new Unit("-");
+ public static final Unit DECA = new Unit("*10", UNARY, 10);
+ public static final Unit HECTO = new Unit("*100", DECA, 10);
+ public static final Unit KILO = new Unit("*1000", HECTO, 10);
+ public static final Unit MEGA = new Unit("*10^6", KILO, 1000);
+ public static final Unit GIGA = new Unit("*10^9", MEGA, 1000);
+ public static final Unit TERA = new Unit("*10^12", GIGA, 1000);
private final String name;
@@ -114,108 +114,97 @@ public class Unit implements Comparable<
public Set<Unit> primaryUnits = new CopyOnWriteArraySet<Unit>();
- public static Unit get( String name )
- {
- return UNITS.get( name );
+ public static Unit get(String name) {
+ return UNITS.get(name);
}
/**
* Constructor for a primary unit
+ *
* @param name
*/
- public Unit( String name )
- {
+ public Unit(String name) {
this.name = name;
this.primary = this;
this.scale = 1;
this.derived = new ArrayList<Unit>();
- this.derived.add( this );
- primaryUnits.add( this );
- UNITS.put( name, this );
+ this.derived.add(this);
+ primaryUnits.add(this);
+ UNITS.put(name, this);
}
/**
* Constructor for a derived unit
+ *
* @param name
* @param derived the unit this unit is derived from
- * @param scale the scale factor to convert to derived unit
+ * @param scale the scale factor to convert to derived unit
*/
- public Unit( String name, Unit derived, long scale )
- {
+ public Unit(String name, Unit derived, long scale) {
this.name = name;
this.primary = derived.isPrimary() ? derived : derived.getPrimary();
this.scale = scale * derived.getScale();
- primary.derived.add( this );
- Collections.sort( primary.derived );
- UNITS.put( name, this );
+ primary.derived.add(this);
+ Collections.sort(primary.derived);
+ UNITS.put(name, this);
}
- public Unit getDerived( String name )
- {
- for ( Unit unit : derived )
- {
- if (unit.name.equals( name ))
- {
+ public Unit getDerived(String name) {
+ for (Unit unit : derived) {
+ if (unit.name.equals(name)) {
return unit;
}
}
return null;
}
- public List<Unit> getDerived()
- {
- return Collections.unmodifiableList( derived );
+ public List<Unit> getDerived() {
+ return Collections.unmodifiableList(derived);
}
- public String getName()
- {
+ public String getName() {
return name;
}
- public long getScale()
- {
+ public long getScale() {
return scale;
}
/**
* Convert value from unit to this unit (if conpatible)
- *
+ *
* @param value value to convert
- * @param unit unit of value
+ * @param unit unit of value
* @return value converted to this unit
*/
- public double convert( double value, Unit unit )
- {
- if ( unit == this )
- {
+ public double convert(final double value, final Unit unit) {
+ if (unit == this) {
return value;
}
- return value * unit.getScale() / this.getScale();
+ if (!isCompatible(unit)) {
+ throw new IllegalArgumentException("unit " + name + " is incompatible with unit " + unit.name);
+ }
+ return value * unit.getScale() / scale;
}
- public boolean isPrimary()
- {
+ public boolean isPrimary() {
return primary == this;
}
- public boolean isCompatible( Unit unit )
- {
+ public boolean isCompatible(Unit unit) {
return primary == unit.getPrimary();
}
- public Unit getPrimary()
- {
+ public Unit getPrimary() {
return this.primary;
}
- public int compareTo( Unit o )
- {
+ public int compareTo(Unit o) {
return scale < o.scale ? -1 : 1;
}
- public String toString()
- {
+ public String toString() {
return name;
}
@@ -223,11 +212,10 @@ public class Unit implements Comparable<
* @see java.lang.Object#hashCode()
*/
@Override
- public int hashCode()
- {
+ public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@@ -235,21 +223,18 @@ public class Unit implements Comparable<
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
- public boolean equals( Object obj )
- {
- if ( this == obj )
+ public boolean equals(Object obj) {
+ if (this == obj)
return true;
- if ( obj == null )
+ if (obj == null)
return false;
- if ( getClass() != obj.getClass() )
+ if (getClass() != obj.getClass())
return false;
final Unit other = (Unit) obj;
- if ( name == null )
- {
- if ( other.name != null )
+ if (name == null) {
+ if (other.name != null)
return false;
- }
- else if ( !name.equals( other.name ) )
+ } else if (!name.equals(other.name))
return false;
return true;
}
Added: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/CounterFactory.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/CounterFactory.java?rev=1507950&view=auto
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/CounterFactory.java (added)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/CounterFactory.java Mon Jul 29 06:20:54 2013
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.counter.factory;
+
+import org.apache.commons.monitoring.Role;
+import org.apache.commons.monitoring.counter.Counter;
+
+public interface CounterFactory {
+ Counter newCounter(final Role role);
+ void counterCreated(final Counter counter);
+}
Added: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/DefaultCounterFactory.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/DefaultCounterFactory.java?rev=1507950&view=auto
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/DefaultCounterFactory.java (added)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/factory/DefaultCounterFactory.java Mon Jul 29 06:20:54 2013
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.counter.factory;
+
+import org.apache.commons.monitoring.MonitoringException;
+import org.apache.commons.monitoring.Role;
+import org.apache.commons.monitoring.configuration.Configuration;
+import org.apache.commons.monitoring.counter.Counter;
+import org.apache.commons.monitoring.counter.DefaultCounter;
+import org.apache.commons.monitoring.util.ClassLoaders;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import java.io.Closeable;
+import java.io.IOException;
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+
+public class DefaultCounterFactory implements CounterFactory, Closeable {
+ private static final boolean JMX = Configuration.isActivated(Configuration.Keys.JMX);
+ private static final MBeanServer SERVER = ManagementFactory.getPlatformMBeanServer();
+
+ private final Collection<ObjectName> toUnregister = Collections.synchronizedList(new ArrayList<ObjectName>());
+
+ @Override
+ public Counter newCounter(final Role role) {
+ return new DefaultCounter(role);
+ }
+
+ @Override
+ public void counterCreated(final Counter counter) {
+ if (!JMX) {
+ return;
+ }
+
+ try {
+ final ObjectName name = new ObjectName("org.apache.commons.monitoring:type=counter,name=" + counter.getMonitor().getKey().getName());
+ SERVER.registerMBean(CounterMBean.class.cast(Proxy.newProxyInstance(ClassLoaders.current(), new Class<?>[] { CounterMBean.class }, new InvocationHandler() {
+ @Override
+ public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
+ return method.invoke(counter, args);
+ }
+ })), name);
+ toUnregister.add(name);
+ } catch (final Exception e) {
+ throw new MonitoringException(e);
+ }
+ }
+
+ @Override
+ public synchronized void close() throws IOException {
+ for (final ObjectName name : toUnregister) {
+ try {
+ SERVER.unregisterMBean(name);
+ } catch (final Exception e) {
+ // no-op
+ }
+ }
+ }
+
+ public static interface CounterMBean extends Counter {
+ }
+}
Added: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/DefaultMetricQueueManager.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/DefaultMetricQueueManager.java?rev=1507950&view=auto
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/DefaultMetricQueueManager.java (added)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/DefaultMetricQueueManager.java Mon Jul 29 06:20:54 2013
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.counter.queuemanager;
+
+import org.apache.commons.monitoring.counter.DefaultCounter;
+
+import java.util.concurrent.locks.Lock;
+
+/**
+ * An alternative using Disruptor would need (take care it doesn't go in the shade):
+ *
+ *
+
+ <dependency>
+ <groupId>com.lmax</groupId>
+ <artifactId>disruptor</artifactId>
+ <version>3.1.1</version>
+ <optional>true</optional>
+ </dependency>
+
+ * look like:
+ *
+ *
+
+import com.lmax.disruptor.EventFactory;
+import com.lmax.disruptor.EventHandler;
+import com.lmax.disruptor.EventTranslator;
+import com.lmax.disruptor.ExceptionHandler;
+import com.lmax.disruptor.RingBuffer;
+import com.lmax.disruptor.SleepingWaitStrategy;
+import com.lmax.disruptor.dsl.Disruptor;
+import com.lmax.disruptor.dsl.ProducerType;
+import org.apache.commons.monitoring.counter.DefaultCounter;
+import org.apache.commons.monitoring.util.DaemonThreadFactory;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class DisruptorMetricQueueManager implements MetricQueueManager, Closeable {
+ private static final Logger LOGGER = Logger.getLogger(DefaultCounter.class.getName());
+
+ private static final int RINGBUFFER_DEFAULT_SIZE = 256 * 1024;
+ private static final long HALF_A_SECOND = 500;
+ private static final int MAX_DRAIN_ATTEMPTS_BEFORE_SHUTDOWN = 20;
+
+ private static final Disruptor<MetricEvent> DISRUPTOR;
+ private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new DaemonThreadFactory("commons-monitoring-")); // thread safety using a single thread ;)
+ static {
+ DISRUPTOR = new Disruptor<MetricEvent>(Factory.INSTANCE, RINGBUFFER_DEFAULT_SIZE, EXECUTOR, ProducerType.MULTI, new SleepingWaitStrategy());
+ DISRUPTOR.handleExceptionsWith(new MetricEventExceptionHandler());
+ DISRUPTOR.handleEventsWith(new MetricEventHandler());
+ DISRUPTOR.start();
+ }
+
+ public static boolean flushRingBuffer() {
+ final RingBuffer<MetricEvent> ringBuffer = DISRUPTOR.getRingBuffer();
+ for (int i = 0; i < MAX_DRAIN_ATTEMPTS_BEFORE_SHUTDOWN; i++) {
+ if (ringBuffer.hasAvailableCapacity(ringBuffer.getBufferSize())) {
+ break;
+ }
+
+ try {
+ Thread.sleep(HALF_A_SECOND);
+ } catch (final InterruptedException e) {
+ // no-op
+ }
+ }
+ return ringBuffer.hasAvailableCapacity(ringBuffer.getBufferSize());
+ }
+
+ @Override
+ public void add(final DefaultCounter metric, final double delta) {
+ DISRUPTOR.publishEvent(new MetricEventTranslator(metric, delta));
+ }
+
+ @Override
+ public void close() throws IOException {
+ DISRUPTOR.shutdown();
+ flushRingBuffer();
+
+ EXECUTOR.shutdown();
+ try {
+ EXECUTOR.awaitTermination(1, TimeUnit.MINUTES);
+ } catch (final InterruptedException e) {
+ // no-op
+ }
+ }
+
+ private static class MetricEvent {
+ private DefaultCounter metric;
+ private double value;
+ }
+
+ private static class Factory implements EventFactory<MetricEvent> {
+ public static final Factory INSTANCE = new Factory();
+
+ @Override
+ public MetricEvent newInstance() {
+ return new MetricEvent();
+ }
+ }
+
+ private class MetricEventTranslator implements EventTranslator<MetricEvent> {
+ private final double value;
+ private final DefaultCounter metric;
+
+ public MetricEventTranslator(final DefaultCounter defaultCounter, final double delta) {
+ this.metric = defaultCounter;
+ this.value = delta;
+ }
+
+ @Override
+ public void translateTo(final MetricEvent event, final long sequence) {
+ event.metric = metric;
+ event.value = value;
+ }
+ }
+
+ private static class MetricEventHandler implements EventHandler<MetricEvent> {
+ @Override
+ public void onEvent(final MetricEvent event, final long sequence, final boolean endOfBatch) throws Exception {
+ event.metric.addInternal(event.value);
+ }
+ }
+
+ private static class MetricEventExceptionHandler implements ExceptionHandler {
+ @Override
+ public void handleEventException(final Throwable ex, final long sequence, final Object event) {
+ LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
+ }
+
+ @Override
+ public void handleOnStartException(final Throwable ex) {
+ LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
+ }
+
+ @Override
+ public void handleOnShutdownException(final Throwable ex) {
+ LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
+ }
+ }
+}
+
+*/
+public class DefaultMetricQueueManager implements MetricQueueManager {
+ @Override
+ public void add(final DefaultCounter baseMetrics, final double delta) {
+ final Lock lock = baseMetrics.getLock();
+ lock.lock();
+ try {
+ baseMetrics.addInternal(delta);
+ } finally {
+ lock.unlock();
+ }
+ }
+}
Added: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/MetricQueueManager.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/MetricQueueManager.java?rev=1507950&view=auto
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/MetricQueueManager.java (added)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/counter/queuemanager/MetricQueueManager.java Mon Jul 29 06:20:54 2013
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.counter.queuemanager;
+
+import org.apache.commons.monitoring.counter.DefaultCounter;
+
+public interface MetricQueueManager {
+ void add(DefaultCounter baseMetrics, double delta);
+}
Modified: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/DefaultMonitor.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/DefaultMonitor.java?rev=1507950&r1=1507949&r2=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/DefaultMonitor.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/DefaultMonitor.java Mon Jul 29 06:20:54 2013
@@ -17,37 +17,103 @@
package org.apache.commons.monitoring.monitors;
-import org.apache.commons.monitoring.Counter;
-import org.apache.commons.monitoring.Gauge;
import org.apache.commons.monitoring.Role;
-import org.apache.commons.monitoring.metrics.RentrantLockCounter;
-import org.apache.commons.monitoring.metrics.RentrantLockGauge;
+import org.apache.commons.monitoring.Visitor;
+import org.apache.commons.monitoring.configuration.Configuration;
+import org.apache.commons.monitoring.counter.Counter;
+import org.apache.commons.monitoring.counter.factory.CounterFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class DefaultMonitor implements Monitor {
+ private static final CounterFactory METRIC_FACTORY = Configuration.newInstance(CounterFactory.class);
+
+ private final ConcurrentMap<Role, Counter> metrics;
+ private final AtomicInteger concurrency;
+ private final Key key;
+ private volatile int maxConcurrency = 0;
+
+ public DefaultMonitor(final Key key) {
+ this.key = key;
+ this.metrics = new ConcurrentHashMap<Role, Counter>();
+ this.concurrency = new AtomicInteger(0);
+ }
-/**
- * A Monitor implementation that creates
- * {@link org.apache.commons.monitoring.Composite} Gauges and Counters.
- *
- * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
- */
-public class DefaultMonitor
- extends ObservableMonitor
-{
+ @Override
+ public Key getKey() {
+ return key;
+ }
- public DefaultMonitor( Key key )
- {
- super( key );
+ @Override
+ public Counter getCounter(final Role role) {
+ if (role == null) {
+ return null;
+ }
+
+ { // if existing use it
+ final Counter existingCounter = metrics.get(role);
+ if (existingCounter != null) {
+ return existingCounter;
+ }
+ }
+
+ // else create it
+ final Counter counter = METRIC_FACTORY.newCounter(role);
+ counter.setMonitor(this);
+
+ final Counter previous = metrics.putIfAbsent(counter.getRole(), counter);
+ if (previous == null) {
+ METRIC_FACTORY.counterCreated(counter);
+ return counter;
+ }
+ return previous;
}
@Override
- protected Counter newCounterInstance( Role role )
- {
- return new RentrantLockCounter( role );
+ public Counter getCounter(final String role) {
+ return getCounter(Role.getRole(role));
}
@Override
- protected Gauge newGaugeInstance( Role role )
- {
- return new RentrantLockGauge( role );
+ public Collection<Role> getRoles() {
+ return Collections.unmodifiableCollection(metrics.keySet());
}
+ @Override
+ public Collection<Counter> getCounters() {
+ return Collections.unmodifiableCollection(metrics.values());
+ }
+
+ @Override
+ public AtomicInteger currentConcurrency() {
+ return concurrency;
+ }
+
+ @Override
+ public void reset() {
+ for (final Counter counter : metrics.values()) {
+ counter.reset();
+ }
+ }
+
+ @Override
+ public void updateConcurrency(int concurrency) {
+ if (concurrency > maxConcurrency) {
+ maxConcurrency = concurrency;
+ }
+ }
+
+ @Override
+ public int getMaxConcurrency() {
+ return maxConcurrency;
+ }
+
+ @Override
+ public void accept(final Visitor visitor) {
+ visitor.visit(this);
+ }
}
Copied: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/Monitor.java (from r1506987, commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Monitor.java)
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/Monitor.java?p2=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/Monitor.java&p1=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Monitor.java&r1=1506987&r2=1507950&rev=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Monitor.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/monitors/Monitor.java Mon Jul 29 06:20:54 2013
@@ -15,56 +15,38 @@
* limitations under the License.
*/
-package org.apache.commons.monitoring;
+package org.apache.commons.monitoring.monitors;
-import static org.apache.commons.monitoring.Unit.Time.MILLISECOND;
+import org.apache.commons.monitoring.Role;
+import org.apache.commons.monitoring.Visitable;
+import org.apache.commons.monitoring.counter.Counter;
import java.util.Collection;
-import java.util.EventListener;
+import java.util.concurrent.atomic.AtomicInteger;
/**
* A <code>Monitor</code> is an abstraction of some application resource that is instrumented with a set of indicators
* (Gauges or Counters).
- * <p>
+ * <p/>
* A Monitor is identified by its Key, that MUST be unique in the application. To ensure this, the Key class defines the
* monitor identifier as a combination of name, subsystem and category.
- * <p>
+ * <p/>
* The <tt>name</tt> is the human-readable representation of the "resource" beeing monitored. A typical use is the fully
* qualified class name + method signature, or the HTTP request path.
- * <p>
+ * <p/>
* The <tt>category</tt> is a grouping attribute to reflect the application layering. Typically for JEE application, you
* will set category to the N-tier layer beeing monitored ("servlet", "service", "persistence").
- * <p>
- * The <tt>subsystem</tt> is a logical grouping, by use-cases. "account", and "user" can be used as subsystem for the
- * application account and user management dedicated components.
- * <p>
+ * <p/>
* You are free to use more complex Key types, by simple subclassing the Key class and providing the adequate
* equals()/hasCode() methods.
- * <p>
+ * <p/>
* The Counters / Gauges used to store monitored application state are retrieved based on a "role" String. The monitor
* can handle as many Metrics as needed, until any of them has a dedicated role. This allows to easily extend the
* monitor by registering custom Metrics.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public interface Monitor
- extends Visitable
-{
- // --- Predefined roles -------------------------------------------------------------------
-
- /** Predefined role key for code performances */
- Role PERFORMANCES = new Role( "performances", MILLISECOND, Metric.Type.COUNTER );
-
- /** Predefined role key for cpu time */
- Role CPU = new Role( "cpu", MILLISECOND, Metric.Type.COUNTER );
-
- /** Predefined role for multi-thread concurrency */
- Role CONCURRENCY = new Role( "concurrency", Unit.UNARY, Metric.Type.GAUGE );
-
- /** Predefined Role for the invocation failure counter */
- Role FAILURES = new Role( "failures", Unit.UNARY, Metric.Type.COUNTER );
-
-
+public interface Monitor extends Visitable {
/**
* @return the monitor key
*/
@@ -74,10 +56,9 @@ public interface Monitor
* Retrieve a Counter
*
* @param role a unique identifier for a Counter in the monitor
- * @param unit the data unit to count
* @return the Counter
*/
- Counter getCounter( String role );
+ Counter getCounter(String role);
/**
* Retrieve or create a Counter in the monitor
@@ -85,39 +66,7 @@ public interface Monitor
* @param role the Counter role in the monitor
* @return the Counter
*/
- Counter getCounter( Role role );
-
- /**
- * Retrieve a Gauge in the monitor
- *
- * @param role a unique identifier for a Gauge in the monitor
- * @return the Gauge
- */
- Gauge getGauge( String role );
-
- /**
- * Retrieve or create a Gauge in the monitor
- *
- * @param role the gauge role in the monitor
- * @return the Gauge
- */
- Gauge getGauge( Role role );
-
- /**
- * Retrieve a Metric.
- *
- * @param role a unique identifier for a Metric in the monitor
- * @return the Metric
- */
- Metric getMetric( String role );
-
- /**
- * Retrieve a Metric in the monitor
- *
- * @param role the Metric role in the monitor
- * @return the Metric
- */
- Metric getMetric( Role role );
+ Counter getCounter(Role role);
/**
* @return an unmodifiable collection of registered Metrics roles
@@ -127,170 +76,85 @@ public interface Monitor
/**
* @return an unmodifiable collection of registered Metrics
*/
- Collection<Metric> getMetrics();
+ Collection<Counter> getCounters();
/**
* Reset all Metrics (don't remove them)
*/
void reset();
+ AtomicInteger currentConcurrency();
+
+ void updateConcurrency(int concurrency);
+
+ int getMaxConcurrency();
+
/**
* Identifier class for Monitors.
- * <p>
+ * <p/>
* The name is expected to define a resource or point to some precise code fragment.
* The category may be used to declare the application technical layer where the monitor
* is registered. The subsystem may be used to declare the logical part the monitored
* element belong to.
- * <p>
- * User may extend this class to define custom keys, just be aware to override the {@ #equals())
- * and {@ #hashCode()} methods to ensure unicity of the Keys.
+ * <p/>
+ * User may extend this class to define custom keys, just be aware to override the {@see #equals())
+ * and {@see #hashCode()} methods to ensure unicity of the Keys.
*/
- public static class Key
- {
+ public static class Key {
public final static String DEFAULT = "default";
private final String name;
private final String category;
- private final String subsystem;
-
- public Key( String name, String category, String subsystem )
- {
+ public Key(final String name, final String category) {
super();
- if (name == null)
- {
- throw new IllegalArgumentException( "A name must be provided" );
+ if (name == null) {
+ throw new IllegalArgumentException("A name must be provided");
}
this.name = name;
this.category = category != null ? category : DEFAULT;
- this.subsystem = subsystem != null ? subsystem : DEFAULT;;
}
@Override
- public String toString()
- {
- StringBuilder stb = new StringBuilder();
- stb.append( "name=" );
- stb.append( name );
- if ( category != null )
- {
- stb.append( "\ncategory=" );
- stb.append( category );
- }
- if ( subsystem != null )
- {
- stb.append( "\nsubsystem=" );
- stb.append( subsystem );
+ public String toString() {
+ final StringBuilder stb = new StringBuilder();
+ stb.append("name=");
+ stb.append(name);
+ if (category != null) {
+ stb.append("\ncategory=");
+ stb.append(category);
}
return stb.toString();
}
@Override
- public int hashCode()
- {
- final int prime = 31;
- int result = 1;
- result = prime * result + ( ( category == null ) ? 0 : category.hashCode() );
- result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
- result = prime * result + ( ( subsystem == null ) ? 0 : subsystem.hashCode() );
- return result;
- }
-
- @Override
- public boolean equals( Object obj )
- {
- if ( this == obj )
- {
+ public boolean equals(final Object o) {
+ if (this == o) {
return true;
}
- if ( obj == null )
- {
+ if (o == null || Key.class != o.getClass()) {
return false;
}
- if ( getClass() != obj.getClass() )
- {
- return false;
- }
- final Key other = (Key) obj;
- if ( category == null )
- {
- if ( other.category != null )
- {
- return false;
- }
- }
- else if ( !category.equals( other.category ) )
- {
- return false;
- }
- if ( name == null )
- {
- if ( other.name != null )
- {
- return false;
- }
- }
- else if ( !name.equals( other.name ) )
- {
- return false;
- }
- if ( subsystem == null )
- {
- if ( other.subsystem != null )
- {
- return false;
- }
- }
- else if ( !subsystem.equals( other.subsystem ) )
- {
- return false;
- }
- return true;
- }
- public String getName()
- {
- return name;
- }
+ final Key key = Key.class.cast(o);
+ return category.equals(key.category) && name.equals(key.name);
- public String getCategory()
- {
- return category;
}
- public String getSubsystem()
- {
- return subsystem;
+ @Override
+ public int hashCode() {
+ int result = name.hashCode();
+ result = 31 * result + category.hashCode();
+ return result;
}
- }
-
-
- /**
- * Listener interface to get notified on montor events
- */
- public interface Listener
- extends EventListener
- {
- void onMetricRegistered( Monitor.Observable monitor, Metric metric );
- }
+ public String getName() {
+ return name;
+ }
- /**
- * A monitor that support the Observer pattern.
- */
- public interface Observable extends Monitor
- {
- /**
- * @param listener listener to get registered
- */
- void addListener( Listener listener );
-
- /**
- * @param listener listener to get removed
- */
- void removeListener( Listener listener );
+ public String getCategory() {
+ return category;
+ }
}
-
-
}
Modified: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/DefaultRepository.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/DefaultRepository.java?rev=1507950&r1=1507949&r2=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/DefaultRepository.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/DefaultRepository.java Mon Jul 29 06:20:54 2013
@@ -17,30 +17,100 @@
package org.apache.commons.monitoring.repositories;
-import org.apache.commons.monitoring.Monitor;
-import org.apache.commons.monitoring.StopWatch;
-import org.apache.commons.monitoring.Monitor.Key;
+import org.apache.commons.monitoring.Visitor;
+import org.apache.commons.monitoring.configuration.Configuration;
import org.apache.commons.monitoring.monitors.DefaultMonitor;
-import org.apache.commons.monitoring.stopwatches.DefaultStopWatch;
+import org.apache.commons.monitoring.monitors.Monitor;
+import org.apache.commons.monitoring.monitors.Monitor.Key;
+import org.apache.commons.monitoring.stopwatches.CounterStopWatch;
+import org.apache.commons.monitoring.stopwatches.StopWatch;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+public class DefaultRepository implements Repository {
+ private final ConcurrentMap<Key, Monitor> monitors = new ConcurrentHashMap<Key, Monitor>(50);
-/**
- * Default Repository implementation
- *
- * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
- */
-public class DefaultRepository extends ObservableRepository
-{
+ protected Monitor newMonitorInstance(final Key key) {
+ return new DefaultMonitor(key);
+ }
+
+ protected Monitor register(final Monitor monitor) {
+ return monitors.putIfAbsent(monitor.getKey(), monitor);
+ }
+
+ @Override
+ public Monitor getMonitor(final Key key) {
+ Monitor monitor = monitors.get(key);
+ if (monitor == null) {
+ monitor = newMonitorInstance(key);
+ final Monitor previous = register(monitor);
+ if (previous != null) {
+ monitor = previous;
+ }
+ }
+ return monitor;
+ }
+
+ @Override
+ public Monitor getMonitor(final String name) {
+ return getMonitor(name, Key.DEFAULT);
+ }
@Override
- protected Monitor newMonitorInstance( Key key )
- {
- return new DefaultMonitor( key );
+ public Monitor getMonitor(final String name, final String category) {
+ return getMonitor(new Monitor.Key(name, category));
}
- public StopWatch start( Monitor monitor )
- {
- return new DefaultStopWatch( monitor );
+ @Override
+ public Collection<Monitor> getMonitors() {
+ return Collections.unmodifiableCollection(monitors.values());
}
+ @Override
+ public Collection<Monitor> getMonitorsFromCategory(final String category) {
+ final Collection<Monitor> filtered = new LinkedList<Monitor>();
+ for (final Monitor monitor : monitors.values()) {
+ if (category.equals(monitor.getKey().getCategory())) {
+ filtered.add(monitor);
+ }
+ }
+ return filtered;
+ }
+
+ @Override
+ public Set<String> getCategories() {
+ final Set<String> categories = new HashSet<String>();
+ for (final Key key : monitors.keySet()) {
+ categories.add(key.getCategory());
+ }
+ return categories;
+ }
+
+ @Override
+ public void clear() {
+ monitors.clear();
+ }
+
+ @Override
+ public void reset() {
+ for (final Monitor monitor : monitors.values()) {
+ monitor.reset();
+ }
+ }
+
+ @Override
+ public StopWatch start(final Monitor monitor) {
+ return new CounterStopWatch(monitor);
+ }
+
+ @Override
+ public void accept(final Visitor visitor) {
+ visitor.visit(this);
+ }
}
Copied: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/Repository.java (from r1506987, commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Repository.java)
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/Repository.java?p2=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/Repository.java&p1=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Repository.java&r1=1506987&r2=1507950&rev=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/Repository.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/repositories/Repository.java Mon Jul 29 06:20:54 2013
@@ -15,10 +15,14 @@
* limitations under the License.
*/
-package org.apache.commons.monitoring;
+package org.apache.commons.monitoring.repositories;
+
+import org.apache.commons.monitoring.Visitable;
+import org.apache.commons.monitoring.configuration.Configuration;
+import org.apache.commons.monitoring.monitors.Monitor;
+import org.apache.commons.monitoring.stopwatches.StopWatch;
import java.util.Collection;
-import java.util.EventListener;
import java.util.Set;
/**
@@ -27,28 +31,23 @@ import java.util.Set;
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public interface Repository
- extends Visitable
-{
+public interface Repository extends Visitable {
+ static final Repository INSTANCE = Configuration.newInstance(Repository.class);
+
/**
* Retrieve or create a monitor it's key
*/
- Monitor getMonitor( Monitor.Key key );
+ Monitor getMonitor(Monitor.Key key);
/**
* Retrieve or create a monitor by name
*/
- Monitor getMonitor( String name );
+ Monitor getMonitor(String name);
/**
* Retrieve or create a monitor by name and category
*/
- Monitor getMonitor( String name, String category );
-
- /**
- * Retrieve or create a monitor by name, category and subsystem
- */
- Monitor getMonitor( String name, String category, String subsystem );
+ Monitor getMonitor(String name, String category);
/**
* @return all monitors registered in the repository
@@ -60,14 +59,7 @@ public interface Repository
* @return all monitors in the repository that declare this category in
* there Key
*/
- Collection<Monitor> getMonitorsFromCategory( String category );
-
- /**
- * @param subsystem a subsystem name
- * @return all monitors in the repository that declare this subsystem in
- * there Key
- */
- Collection<Monitor> getMonitorsFromSubSystem( String subsystem );
+ Collection<Monitor> getMonitorsFromCategory(String category);
/**
* @return the categories declared by monitors in the repository
@@ -75,11 +67,6 @@ public interface Repository
Set<String> getCategories();
/**
- * @return the subsystems declared by monitors in the repository
- */
- Set<String> getSubSystems();
-
- /**
* Reset the repository : all existing monitors are destroyed and data are lost.
*/
void clear();
@@ -92,42 +79,9 @@ public interface Repository
/**
* Start a StopWatch to monitor execution
+ *
* @param monitor the monitor associated with the process
* @return a running StopWatch
*/
- StopWatch start( Monitor monitor );
-
- /**
- * A repository that support the Observer pattern.
- */
- public interface Observable extends Repository
- {
- /**
- * @param listener listener to get registered
- */
- void addListener( Listener listener );
-
- /**
- * @param listener listener to get removed
- */
- void removeListener( Listener listener );
-
- }
-
- /**
- * Listener interface to get notified on repository events
- */
- public static interface Listener
- extends EventListener
- {
- /**
- * A monitor has just been created. Can be used to add custom Metrics or
- * to register Metric.Listener for all monitors that declare the same category or
- * subsystem.
- *
- * @param monitor
- */
- void newMonitorInstance( Monitor monitor );
- }
-
+ StopWatch start(Monitor monitor);
}
Copied: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/CounterStopWatch.java (from r1506987, commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/SimpleStopWatch.java)
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/CounterStopWatch.java?p2=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/CounterStopWatch.java&p1=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/SimpleStopWatch.java&r1=1506987&r2=1507950&rev=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/SimpleStopWatch.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/CounterStopWatch.java Mon Jul 29 06:20:54 2013
@@ -17,115 +17,59 @@
package org.apache.commons.monitoring.stopwatches;
-import static org.apache.commons.monitoring.Unit.Time.NANOSECOND;
-
-import org.apache.commons.monitoring.Monitor;
import org.apache.commons.monitoring.Role;
-import org.apache.commons.monitoring.StopWatch;
+import org.apache.commons.monitoring.monitors.Monitor;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.apache.commons.monitoring.counter.Unit.Time.NANOSECOND;
/**
* Simple implementation of StopWatch that estimate monitored element execution time.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public class SimpleStopWatch
- implements StopWatch
-{
- /** Monitor that is notified of process execution state */
- public final Monitor monitor;
-
- /** Time the probe was started */
+public class CounterStopWatch implements StopWatch {
+ protected final Monitor monitor;
protected final long startedAt;
-
- /** Time the probe was stopped */
+ protected final Role role;
+ protected final AtomicInteger concurrencyCounter;
protected long stopedAt;
-
- /** Time the probe was paused */
protected long pauseDelay;
-
- /** flag for stopped probe */
protected boolean stoped;
-
- /** flag for paused probe */
protected boolean paused;
- private Role role;
-
- public SimpleStopWatch( Monitor monitor )
- {
- this( monitor, Monitor.PERFORMANCES );
- }
-
- /**
- * Constructor.
- * <p>
- * The monitor can be set to null to use the StopWatch without the monitoring infrastructure.
- *
- * @param monitor the monitor associated with the process to be monitored
- */
- public SimpleStopWatch( Monitor monitor, Role role )
- {
- super();
- this.role = role;
+ public CounterStopWatch(final Monitor monitor) {
+ this.role = Role.PERFORMANCES;
this.monitor = monitor;
startedAt = nanotime();
+
+ concurrencyCounter = monitor.currentConcurrency();
+ final int concurrency = concurrencyCounter.incrementAndGet();
+ monitor.updateConcurrency(concurrency);
}
- /**
- * Returns the current value of the most precise available system timer, in nanoseconds. The real precision depends
- * on the JVM and the underlying system. On JRE before java5, <tt>backport-util-concurrent</tt> provides some
- * limited support for equivalent timer.
- *
- * @see System#nanoTime()
- * @return time in nanosecond
- */
- protected long nanotime()
- {
+ protected long nanotime() {
return System.nanoTime();
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#getElapsedTime()
- */
- public long getElapsedTime()
- {
- if ( stoped || paused )
- {
- return stopedAt - startedAt - pauseDelay;
- }
- else
- {
- // Still running !
+ public long getElapsedTime() {
+ if (!stoped && !paused) {
return nanotime() - startedAt - pauseDelay;
}
+ return stopedAt - startedAt - pauseDelay;
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#pause()
- */
- public StopWatch pause()
- {
- if ( !paused && !stoped )
- {
+ public StopWatch pause() {
+ if (!paused && !stoped) {
stopedAt = nanotime();
paused = true;
}
return this;
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#resume()
- */
- public StopWatch resume()
- {
- if ( paused && !stoped )
- {
+ public StopWatch resume() {
+ if (paused && !stoped) {
pauseDelay = nanotime() - stopedAt;
paused = false;
stopedAt = 0;
@@ -133,19 +77,10 @@ public class SimpleStopWatch
return this;
}
- /**
- * {@inheritDoc}
- *
- * @return TODO
- * @see org.apache.commons.monitoring.StopWatch#stop()
- */
- public StopWatch stop()
- {
- if ( !stoped )
- {
- long t = nanotime();
- if ( paused )
- {
+ public StopWatch stop() {
+ if (!stoped) {
+ final long t = nanotime();
+ if (paused) {
pauseDelay = t - stopedAt;
}
stopedAt = t;
@@ -155,122 +90,58 @@ public class SimpleStopWatch
return this;
}
- protected void doStop()
- {
- monitor.getCounter( role ).add( getElapsedTime(), NANOSECOND );
+ protected void doStop() {
+ monitor.getCounter(role).add(getElapsedTime(), NANOSECOND);
+ concurrencyCounter.decrementAndGet();
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#stop(boolean)
- */
- public StopWatch stop( boolean canceled )
- {
- if ( canceled )
- {
+ public StopWatch stop(boolean canceled) {
+ if (canceled) {
cancel();
- }
- else
- {
+ } else {
stop();
}
return this;
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#cancel()
- */
- public StopWatch cancel()
- {
- if ( !stoped )
- {
+ public StopWatch cancel() {
+ if (!stoped) {
stoped = true;
doCancel();
}
return this;
}
- protected void doCancel()
- {
-
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Monitored application should use a <code>try/finally</code> block to ensure on of {@link #stop()} or
- * {@link #cancel()} method is invoked, even when an exception occurs. To avoid StopWatches to keep running if the
- * application didn't follow this recommendation, the finalizer is used to cancel the StopWatch and will log a
- * educational warning.
- *
- * @see java.lang.Object#finalize()
- */
- protected void finalize()
- {
- // This probe is reclaimed by garbage-collector and still running,
- // the monitored code "forgot" to stop/cancel it properly.
- if ( !stoped && ( monitor != null ) )
- {
- System.err.println( "WARNING : Execution for " + monitor.getKey().toString() + " was not stoped properly. "
- + "This can result in wrong concurrency monitoring. " + "Use try/finally blocks to avoid this warning" );
- }
+ protected void doCancel() {
+ // no-op
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#isStoped()
- */
- public boolean isStoped()
- {
+ public boolean isStoped() {
return stoped;
}
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#isPaused()
- */
- public boolean isPaused()
- {
+ public boolean isPaused() {
return paused;
}
+ public Monitor getMonitor() {
+ return monitor;
+ }
+
@Override
- public String toString()
- {
- StringBuffer stb = new StringBuffer();
- if ( monitor != null )
- {
- stb.append( "Execution for " ).append( monitor.getKey().toString() ).append( " " );
- }
- if ( paused )
- {
- stb.append( "paused after " ).append( getElapsedTime() ).append( "ns" );
- }
- else if ( stoped )
- {
- stb.append( "stoped after " ).append( getElapsedTime() ).append( "ns" );
- }
- else
- {
- stb.append( "running for " ).append( getElapsedTime() ).append( "ns" );
+ public String toString() {
+ final StringBuilder stb = new StringBuilder();
+ if (monitor != null) {
+ stb.append("Execution for ").append(monitor.getKey().toString()).append(" ");
+ }
+ if (paused) {
+ stb.append("paused after ").append(getElapsedTime()).append("ns");
+ } else if (stoped) {
+ stb.append("stoped after ").append(getElapsedTime()).append("ns");
+ } else {
+ stb.append("running for ").append(getElapsedTime()).append("ns");
}
return stb.toString();
}
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.commons.monitoring.StopWatch#getMonitor()
- */
- public Monitor getMonitor()
- {
- return monitor;
- }
-
}
\ No newline at end of file
Copied: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/StopWatch.java (from r1506987, commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/StopWatch.java)
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/StopWatch.java?p2=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/StopWatch.java&p1=commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/StopWatch.java&r1=1506987&r2=1507950&rev=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/StopWatch.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/stopwatches/StopWatch.java Mon Jul 29 06:20:54 2013
@@ -15,41 +15,43 @@
* limitations under the License.
*/
-package org.apache.commons.monitoring;
+package org.apache.commons.monitoring.stopwatches;
+
+import org.apache.commons.monitoring.monitors.Monitor;
/**
* Instrumentation tool to compute resource consumption of some code fragment execution.
- * <p>
+ * <p/>
* StopWatch implementation is supposed not to be thread-safe and to be a one-shot tool. Don't
* share it beetween threads, don't try to reuse it.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public interface StopWatch
-{
+public interface StopWatch {
/**
* @return Elapsed time (in nanoseconds) for the monitored process, not
* including paused time
*/
- public abstract long getElapsedTime();
+ long getElapsedTime();
/**
* Temporary stop the StopWatch. Elapsed time calculation will not include
* time spent in paused mode.
*/
- public abstract StopWatch pause();
+ StopWatch pause();
/**
* Resume the StopWatch after a pause.
*/
- public abstract StopWatch resume();
+ StopWatch resume();
/**
* Stop monitoring the process. A StopWatch created with
- * {@link #start(Monitor)} cannot be re-used after stopped has been called.
+ * {@link #start(org.apache.commons.monitoring.monitors.Monitor)} cannot be re-used after stopped has been called.
+ *
* @return TODO
*/
- public abstract StopWatch stop();
+ StopWatch stop();
/**
* Convenience method to stop or cancel a Stopwatch depending on success of
@@ -58,33 +60,33 @@ public interface StopWatch
* @param canceled
* @return time elapsed since the probe has been started
*/
- public abstract StopWatch stop( boolean canceled );
+ StopWatch stop(boolean canceled);
/**
* Cancel monitoring. Elapsed time will not be computed and will not be
* published to the monitor.
- * <p>
+ * <p/>
* In some circumstances you want to monitor time elapsed from early stage
* of computation, and discover latter if the computed data is relevant. For
* example, monitoring a messaging system, but beeing interested only by
* some types of messages. In such case, a StopWatch can be started early
* and canceled when the application is able to determine it's relevancy.
- * <p>
+ * <p/>
* In any way, the probe will still report thread concurrency even if
* canceled.
*/
- public abstract StopWatch cancel();
+ StopWatch cancel();
/**
* @return <code>true</code> if the StopWatch has been stopped
*/
- public abstract boolean isStoped();
+ boolean isStoped();
/**
* @return <code>true</code> if the StopWatch has been paused
*/
- public abstract boolean isPaused();
+ boolean isPaused();
- public abstract Monitor getMonitor();
+ Monitor getMonitor();
}
\ No newline at end of file
Modified: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/ClassLoaders.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/ClassLoaders.java?rev=1507950&r1=1507949&r2=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/ClassLoaders.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/ClassLoaders.java Mon Jul 29 06:20:54 2013
@@ -16,10 +16,8 @@
*/
package org.apache.commons.monitoring.util;
-public final class ClassLoaders
-{
- public static ClassLoader current()
- {
+public final class ClassLoaders {
+ public static ClassLoader current() {
final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
if (tccl != null) {
return tccl;
@@ -27,8 +25,7 @@ public final class ClassLoaders
return ClassLoaders.class.getClassLoader();
}
- private ClassLoaders()
- {
+ private ClassLoaders() {
// no-op
}
}
Added: commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/DaemonThreadFactory.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/DaemonThreadFactory.java?rev=1507950&view=auto
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/DaemonThreadFactory.java (added)
+++ commons/sandbox/monitoring/trunk/core/src/main/java/org/apache/commons/monitoring/util/DaemonThreadFactory.java Mon Jul 29 06:20:54 2013
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.util;
+
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public final class DaemonThreadFactory implements ThreadFactory {
+ private final AtomicInteger id = new AtomicInteger(1);
+ private final String baseName;
+
+ public DaemonThreadFactory(final String baseName) {
+ this.baseName = baseName;
+ }
+
+ @Override
+ public Thread newThread(final Runnable r) {
+ final Thread thread = new Thread(Thread.currentThread().getThreadGroup(), r, baseName + id.getAndIncrement());
+ if (!thread.isDaemon()) {
+ thread.setDaemon(true);
+ }
+ if (thread.getPriority() != Thread.NORM_PRIORITY) {
+ thread.setPriority(Thread.NORM_PRIORITY);
+ }
+ return thread;
+ }
+}
Modified: commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/UnitTest.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/UnitTest.java?rev=1507950&r1=1507949&r2=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/UnitTest.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/UnitTest.java Mon Jul 29 06:20:54 2013
@@ -17,37 +17,33 @@
package org.apache.commons.monitoring;
-import static junit.framework.Assert.assertEquals;
-import static org.apache.commons.monitoring.Unit.Time.HOUR;
-import static org.apache.commons.monitoring.Unit.Time.MICROSECOND;
-import static org.apache.commons.monitoring.Unit.Time.MILLISECOND;
-import static org.apache.commons.monitoring.Unit.Time.NANOSECOND;
-import static org.apache.commons.monitoring.Unit.Time.SECOND;
-
import org.junit.Test;
+import static org.apache.commons.monitoring.counter.Unit.Time.HOUR;
+import static org.apache.commons.monitoring.counter.Unit.Time.MICROSECOND;
+import static org.apache.commons.monitoring.counter.Unit.Time.MILLISECOND;
+import static org.apache.commons.monitoring.counter.Unit.Time.NANOSECOND;
+import static org.apache.commons.monitoring.counter.Unit.Time.SECOND;
+import static org.junit.Assert.assertEquals;
+
/**
- *
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public class UnitTest
-{
+public class UnitTest {
@Test
- public void derived()
- {
- assertEquals( NANOSECOND, HOUR.getPrimary() );
- assertEquals( NANOSECOND, NANOSECOND.getDerived( "ns" ) );
- assertEquals( MICROSECOND, NANOSECOND.getDerived( "µs" ) );
- assertEquals( MILLISECOND, NANOSECOND.getDerived( "ms" ) );
- assertEquals( SECOND, NANOSECOND.getDerived( "s" ) );
+ public void derived() {
+ assertEquals(NANOSECOND, HOUR.getPrimary());
+ assertEquals(NANOSECOND, NANOSECOND.getDerived("ns"));
+ assertEquals(MICROSECOND, NANOSECOND.getDerived("µs"));
+ assertEquals(MILLISECOND, NANOSECOND.getDerived("ms"));
+ assertEquals(SECOND, NANOSECOND.getDerived("s"));
}
@Test
- public void scales()
- {
- assertEquals( 1L, NANOSECOND.getScale() );
- assertEquals( 1000L, MICROSECOND.getScale() );
- assertEquals( 1000000L, MILLISECOND.getScale() );
- assertEquals( 1000000000L, SECOND.getScale() );
+ public void scales() {
+ assertEquals(1L, NANOSECOND.getScale());
+ assertEquals(1000L, MICROSECOND.getScale());
+ assertEquals(1000000L, MILLISECOND.getScale());
+ assertEquals(1000000000L, SECOND.getScale());
}
}
Modified: commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/counter/CounterBench.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/counter/CounterBench.java?rev=1507950&r1=1506987&r2=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/counter/CounterBench.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/counter/CounterBench.java Mon Jul 29 06:20:54 2013
@@ -1,62 +1,61 @@
-package org.apache.commons.monitoring.metrics;
-import static junit.framework.Assert.assertEquals;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.monitoring.counter;
+
+import org.apache.commons.monitoring.Role;
+import org.junit.Test;
+
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import org.apache.commons.monitoring.Counter;
-import org.apache.commons.monitoring.Monitor;
-import org.apache.commons.monitoring.Unit;
-import org.apache.commons.monitoring.metrics.RentrantLockCounter;
-import org.apache.commons.monitoring.metrics.SynchronizedCounter;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
-public class CounterBench implements Runnable
-{
- private static final int THREADS = 5;
-
- private static final int LOOPS = 100;
+public class CounterBench implements Runnable {
+ private static final int THREADS = 30;
+ private static final int LOOPS = 20000000;
private Counter counter;
-
private String mode;
-
@Test
- public void synchronizedCounter() throws Exception
- {
- mode = "SynchronizedCounter";
- counter = new SynchronizedCounter( Monitor.FAILURES );
- runConcurrent();
- }
-
- @Test
- public void rentrantLockCounter() throws Exception
- {
+ public void defaultCounter() throws Exception {
mode = "RentrantLockCounter";
- counter = new RentrantLockCounter( Monitor.FAILURES );
+ counter = new DefaultCounter(Role.FAILURES);
runConcurrent();
}
-
- private void runConcurrent()
- throws InterruptedException
- {
- long start = System.nanoTime();
- ExecutorService pool = Executors.newFixedThreadPool( THREADS );
- for (int i = 0 ; i < LOOPS; i++)
- {
- pool.submit( this );
+ private void runConcurrent() throws InterruptedException {
+ final long start = System.nanoTime();
+ final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
+ for (int i = 0; i < LOOPS; i++) {
+ pool.submit(this);
}
- pool.awaitTermination( 60, TimeUnit.SECONDS );
- assertEquals( LOOPS, counter.getSum() );
- System.out.printf( "%s : %,d ns/operation %n", mode, ( System.nanoTime() - start ) /LOOPS);
+ pool.shutdown();
+ pool.awaitTermination(60, TimeUnit.SECONDS);
+
+ final long duration = System.nanoTime() - start;
+ System.out.printf("%s : %,d ns/operation %n\n", mode, duration / LOOPS);
+ assertEquals(LOOPS, counter.getSum(), 0);
}
- public void run()
- {
- counter.add( 1, Unit.UNARY );
+ public void run() {
+ counter.add(1, Unit.UNARY);
}
}
Modified: commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/repositories/DefaultRepositoryTest.java
URL: http://svn.apache.org/viewvc/commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/repositories/DefaultRepositoryTest.java?rev=1507950&r1=1507949&r2=1507950&view=diff
==============================================================================
--- commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/repositories/DefaultRepositoryTest.java (original)
+++ commons/sandbox/monitoring/trunk/core/src/test/java/org/apache/commons/monitoring/repositories/DefaultRepositoryTest.java Mon Jul 29 06:20:54 2013
@@ -17,62 +17,38 @@
package org.apache.commons.monitoring.repositories;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertSame;
-import static junit.framework.Assert.assertTrue;
+import org.apache.commons.monitoring.monitors.Monitor;
+import org.apache.commons.monitoring.monitors.Monitor.Key;
+import org.junit.Test;
import java.util.Collection;
import java.util.Set;
-import org.apache.commons.monitoring.Monitor;
-import org.apache.commons.monitoring.Repository;
-import org.apache.commons.monitoring.Monitor.Key;
-import org.apache.commons.monitoring.repositories.DefaultRepository;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
-public class DefaultRepositoryTest
-{
+public class DefaultRepositoryTest {
@Test
public void categories()
- throws Exception
- {
+ throws Exception {
Repository repository = new DefaultRepository();
- Monitor foo = repository.getMonitor( "foo", "test" );
- repository.getMonitor( "bar", "junit" );
- repository.getMonitor( "just-a-name" );
+ Monitor foo = repository.getMonitor("foo", "test");
+ repository.getMonitor("bar", "junit");
+ repository.getMonitor("just-a-name");
Set<String> categories = repository.getCategories();
- assertTrue( categories.contains( "test" ) );
- assertTrue( categories.contains( "junit" ) );
- assertTrue( categories.contains( Key.DEFAULT ) );
- assertEquals( 3, categories.size() );
-
- Collection<Monitor> monitors = repository.getMonitorsFromCategory( "test" );
- assertEquals( 1, monitors.size() );
- assertSame( foo, monitors.iterator().next() );
- }
-
- @Test
- public void subsystem()
- throws Exception
- {
- Repository repository = new DefaultRepository();
- Monitor foo = repository.getMonitor( "foo", "test", "test" );
- repository.getMonitor( "bar", "junit", "fake" );
- repository.getMonitor( "just-a-name" );
-
- Set<String> subsystems = repository.getSubSystems();
- assertTrue( subsystems.contains( "test" ) );
- assertTrue( subsystems.contains( "fake" ) );
- assertTrue( subsystems.contains( Key.DEFAULT ) );
- assertEquals( 3, subsystems.size() );
-
- Collection<Monitor> monitors = repository.getMonitorsFromSubSystem( "test" );
- assertEquals( 1, monitors.size() );
- assertSame( foo, monitors.iterator().next() );
+ assertTrue(categories.contains("test"));
+ assertTrue(categories.contains("junit"));
+ assertTrue(categories.contains(Key.DEFAULT));
+ assertEquals(3, categories.size());
+
+ Collection<Monitor> monitors = repository.getMonitorsFromCategory("test");
+ assertEquals(1, monitors.size());
+ assertSame(foo, monitors.iterator().next());
}
}