com.addc.commons.statistcs.collector.Accumulator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of addc-statistics Show documentation
Show all versions of addc-statistics Show documentation
The addc-statistics library supplies classes for collecting statistics including counters, timers and accumulators and exposing these
as MBeans.
package com.addc.commons.statistcs.collector;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import com.addc.commons.Mutex;
import com.addc.commons.jmx.JmxBeanImpl;
import com.addc.commons.string.LongFormatter;
/**
* The Accumulator supplies a class for accumulating sizes of events
*/
public class Accumulator extends JmxBeanImpl implements IMbAccumulator {
private final String name;
private long accumulated;
private long eventCount;
private final Mutex lock= new Mutex();
/**
* Create new Accumulator
* @param name The name for the accumulator
*/
public Accumulator(String name) {
super(IMbAccumulator.class);
this.name= name;
}
@Override
public String getName() {
return name;
}
/**
* Add a value to the accumulator and increment the event counter
* @param value The value to add
*/
public void add(long value) {
synchronized (lock) {
eventCount++;
accumulated+= value;
}
}
/**
* Get the sum of all the values added to the accumulator
* @return the sum of all the values added to the accumulator
*/
public long getAccumulated() {
long ret;
synchronized (lock) {
ret= accumulated;
}
return ret;
}
@Override
public String getTotal() {
return LongFormatter.getInstance().format(getAccumulated());
}
@Override
public long getEventCount() {
long ret;
synchronized(lock) {
ret= eventCount;
}
return ret;
}
@Override
public String getAverage() {
String ret;
synchronized(lock) {
ret= LongFormatter.getInstance().format(accumulated/eventCount);
}
return ret;
}
@Override
protected String getDescription(MBeanInfo info) {
return "Accumulator to obtain totals";
}
@Override
protected String getDescription(MBeanAttributeInfo info) {
if ("Name".equals(info.getName())) {
return "The name of this Accumulator";
}
if ("EventCount".equals(info.getName())) {
return "The number events that were accumulated";
}
if ("Total".equals(info.getName())) {
return "The total accumulated as bytes/kBytes/MBytes";
}
if ("Average".equals(info.getName())) {
return "The average size of the events as bytes/kBytes/MBytes";
}
return super.getDescription(info);
}
/**
* Clear the accumulator setting counters and totals to 0
*/
public void clear() {
synchronized(lock) {
eventCount= 0L;
accumulated= 0L;
}
}
}