Skip to content

Instantly share code, notes, and snippets.

@kofemann
Created September 25, 2013 16:12
Show Gist options
  • Save kofemann/6702006 to your computer and use it in GitHub Desktop.
Save kofemann/6702006 to your computer and use it in GitHub Desktop.
Expose Google's guava Cache vie JMX
public interface GuavaCacheMXBean {
public long getRequestCount();
public long getHitCount();
public double getHitRate();
public long getMissCount();
public double getMissRate();
public long getLoadCount();
public long getLoadSuccessCount();
public long getLoadExceptionCount();
public double getLoadExceptionRate();
public long getTotalLoadTime();
public double getAverageLoadPenalty();
public long getEvictionCount();
public long getSize();
public void cleanUp();
public void invalidateAll();
}
import java.lang.management.ManagementFactory;
import javax.management.*;
/**
* A JMX wrapper for google's Guava Cache
*/
public class GuavaCacheMXBeanImpl implements GuavaCacheMXBean {
private final com.google.common.cache.Cache _cache;
public GuavaCacheMXBeanImpl(String cname, com.google.common.cache.Cache cache) {
_cache = cache;
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
String name = String.format("%s:type=Cache,name=%s",
_cache.getClass().getPackage().getName(), cname);
ObjectName mxBeanName = new ObjectName(name);
if (!server.isRegistered(mxBeanName)) {
server.registerMBean(this, new ObjectName(name));
}
} catch (MalformedObjectNameException | InstanceAlreadyExistsException
| MBeanRegistrationException | NotCompliantMBeanException ex) {
// NOP
}
}
@Override
public long getRequestCount() {
return _cache.stats().requestCount();
}
@Override
public long getHitCount() {
return _cache.stats().hitCount();
}
@Override
public double getHitRate() {
return _cache.stats().hitRate();
}
@Override
public long getMissCount() {
return _cache.stats().missCount();
}
@Override
public double getMissRate() {
return _cache.stats().missRate();
}
@Override
public long getLoadCount() {
return _cache.stats().loadCount();
}
@Override
public long getLoadSuccessCount() {
return _cache.stats().loadSuccessCount();
}
@Override
public long getLoadExceptionCount() {
return _cache.stats().loadExceptionCount();
}
@Override
public double getLoadExceptionRate() {
return _cache.stats().loadExceptionRate();
}
@Override
public long getTotalLoadTime() {
return _cache.stats().totalLoadTime();
}
@Override
public double getAverageLoadPenalty() {
return _cache.stats().averageLoadPenalty();
}
@Override
public long getEvictionCount() {
return _cache.stats().evictionCount();
}
@Override
public long getSize() {
return _cache.size();
}
@Override
public void cleanUp() {
_cache.cleanUp();
}
@Override
public void invalidateAll() {
_cache.invalidateAll();
}
}
@idcmp
Copy link

idcmp commented Dec 22, 2014

This is awesome! Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment