- Overview
- Package structure
- Conceptual model
- Installation
- Quick start
- Usage examples
- Timing a block and recording its duration
- Counting events with different semantics
- Watching a mutable object
- Timing a method with the AOP annotation
- Pull-based Prometheus scrape
- Pushing to JMX
- Pushing to Datadog
- Pushing to AWS CloudWatch
- Reporting JVM state with a feature
- Custom parser for a bespoke meter
- Behavioral reference
- Error model
- Defaults reference
- Operational notes
- Troubleshooting
- Limitations and known issues
- Summary
The smallmind-claxon module is an in-process metrics framework: application code
calls Instrument.with(…).update(…) (or runs a timed block through on(…)),
a background registry thread rolls up the aggregates on a fixed cadence, and one or
more Emitter instances ship the resulting Quantity readings to whatever backend
is configured — CloudWatch, Datadog, Prometheus, JMX, a log stream, or a REST
endpoint.
It is organised as a single parent POM (smallmind-claxon) with four child modules
— claxon-registry, claxon-emitter (itself six subprojects), claxon-http, and
claxon-exotic:
-
claxon-registry— the core. DefinesClaxonRegistry, theMeter/MeterBuilderfamily, theAggregateprimitives, the@InstrumentedAOP annotation and advice, the JSON parsers used by that annotation, the Spring factory beans, and theInstrumentfaçade that lets call sites request a meter without holding a reference to the registry. -
claxon-emitter-*— concreteEmitterimplementations, one per backend (aws,datadog,jmx,message,noop,prometheus). Each is a separate Maven artifact that pulls in only the dependencies its backend needs. -
claxon-http— a single JAX-RS resource,EmitterResource, that exposes pull-style emitters (like Prometheus) over HTTP at/org/smallmind/claxon/emitter/{name}. -
claxon-exotic— extraFeatureimplementations that produce registry-level measurements without a caller. Today the module shipsProfileFeature, which samples fifteen JVM and OS metrics per cycle.
Instrumenting a Java service is usually a tradeoff between three things: the shape of the metric primitives the application programmer sees, the cost of producing a reading on the hot path, and the flexibility of the emission side. Most metric libraries pick two of the three. Claxon aims at all three and makes a specific set of design decisions to keep them compatible:
-
Call-site simplicity without coupling to a backend. Application code writes
Instrument.with(MyClass.class, new TallyBuilder()).update(1)and never references CloudWatch, StatsD, Prometheus, or JMX. The backend is selected entirely at registry-construction time by binding emitters. -
Separation of measurement, aggregation, and emission. The four layers —
Aggregate(lock-free / fine-grained concurrency primitives),Meter(domain-level concepts like Tally/Gauge/Histogram),Emitter(format and transport), andClaxonRegistry(lifecycle and dispatch) — are orthogonal. A new aggregate, meter, or backend can be added without touching the others. -
A fail-safe façade that never crashes the caller.
Instrument.with(…)returns anUnpluggedInstrumentationwhen no registry is installed, and the registry substitutes aNoOpMeterwhen itsNamingStrategyrejects a caller. Code that records metrics cannot accidentally NPE or throw because metrics are misconfigured or not yet wired; only the install step,Instrument.register, throws, and only on a thread with no per-application binding. -
AOP for mechanical instrumentation.
@Instrumentedon a method or constructor turns into an around-advice that resolves aMeterBuilderfrom a JSON string at weave time and records execution time on every invocation, with both constant and parameter-derived tags, without the call site having to be aware of Claxon at all. -
Push-and-pull emission in the same registry. Some backends want data pushed to them on a schedule (CloudWatch, Datadog, JMX, a logger); others expect to scrape a process (Prometheus). Claxon models this explicitly with
PushEmitter/PullEmittersubclasses and anEmitterMethodenum, so a single registry can drive both.
The resulting API is small enough to hold in your head: one façade class, six meter types, seven emitter types, two naming strategies, one annotation. Most of the rest is wiring.
-
Keeps a registry of live meters, keyed by
(caller class, tag array).ClaxonRegistry.register(…)is lazy and idempotent; meters are built on first access via aMeterBuilderand cached for all subsequent calls. -
Runs one daemon thread per registry that wakes on
ClaxonConfiguration.getCollectionStint(), sweeps tracked objects for garbage-collected referents, polls every configuredFeature, polls every cachedMeter, and dispatches the resultingQuantity[]to every boundEmitter. -
Provides six meter types for the common shapes of numeric measurement:
Tally(running counter),Gauge(min/max/average),Speedometer(min/max
count/rate over a sliding window),Tachometer(count/rate only),Histogram(HdrHistogram-backed with percentiles),Trace(multi-window EWMA in the Unix load-average style). -
Attaches tags at three levels — registry-wide (
registryTags), per-meter (meterTags), and per-call-site (passed throughInstrument.with(…)) — and merges them in that order on every emission. -
Ships AOP instrumentation (
@Instrumented) that turns a single annotation into a timed-and-tagged meter, with constant tags, parameter-derived tags, configurableTimeUnit, and an on/off switch. -
Ships Spring factory beans for every wiring point (
ClaxonRegistryFactoryBean,StintFactoryBean,TagFactoryBean, plus one per emitter) so a typical application can assemble a registry entirely in XML. -
Exposes pull emitters over HTTP via
EmitterResource, making the Prometheus scrape endpoint a one-line bean declaration rather than a hand-rolled servlet.
-
It does not expose a distributed tracing API. The
Tracemeter name refers to EWMAs in the Unix-load-average sense, not to span/trace primitives. -
It does not define a wire format of its own. Serialisation is the emitter’s responsibility — CloudWatch dimensions, StatsD counters and gauges, JMX attributes, Prometheus text exposition, or a plain
Consumer<String>. -
It does not store or query historical data. The registry is transient; every collection round is independent, and readings are forwarded, not archived.
-
It does not orchestrate multi-node aggregation. Each process runs its own registry; rollup across nodes is the backend’s job.
The registry carries the core concepts and all the code the other modules link against.
| Class | Role |
|---|---|
|
Central hub. Schedules a daemon collection task on a single-thread
|
|
Configuration bag. Supplies the |
|
Static façade over the registry. |
|
The per-application registry holders. The context flavor stores the
registry in |
|
The fluent call-site API. |
|
The aggregation shapes. |
|
The |
|
The transport contract. |
|
The wire unit. |
|
An immutable |
|
Abstraction over |
|
Maps caller classes to meter names. |
|
Holds tracked objects in |
|
Registry-level metric source with no caller — |
|
JSON-carrier records for histogram percentiles ( |
These are the lock-free or fine-grained-locking primitives that sit under the
meters. They are exposed as a package because they are independently useful:
Bounded alone is a running min/max; Paced alone is a rate counter.
| Aggregate | Role |
|---|---|
|
Monotonic counter backed by |
|
Running arithmetic mean. Uses |
|
Running minimum and maximum via paired |
|
Count and rate over a sliding window. Uses a |
|
HdrHistogram with double-buffered |
|
Continuous-decay EWMA: |
|
A collection of EWMAs with one per configured window, evaluated in parallel.
Default configuration matches Unix |
|
Record: |
The six concrete meter implementations, each with a corresponding
MeterBuilder. Every meter accepts update(long) and returns a
Quantity[] from record(); the differences are what they measure and what
quantities they emit.
| Meter | Emits | Aggregates |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
One quantity per |
|
AOP advice and annotation wiring, built on the dev.aspectj compile-time
weaver configured in claxon/pom.xml.
| Element | Role |
|---|---|
|
Method/constructor annotation. Parameters: |
|
The around-advice. Pointcut: `(execution(@Instrumented * * (..)) |
initialization(@Instrumented new(..)))
&& @annotation(instrumented) |
|
|
Nested-only annotations ( |
|
|
|
|
Five ready-to-use InstrumentedParser implementations — one per configurable
meter type — plus the @Doppelganger-generated view classes they read.
| Parser | Behaviour |
|---|---|
|
JSON is ignored; returns a default-constructed |
|
Deserialises a |
|
Transfers |
|
Transfers |
The Stint and TimeUnit fields in the properties use StintXmlAdapter /
TimeUnitEnumXmlAdapter to accept shorthand forms like
{"time": 2, "timeUnit": "SECONDS"}.
The registry’s own Spring wiring. One FactoryBean per bean that cannot be
configured with bean references alone.
| Factory bean | Produces |
|---|---|
|
|
|
|
|
|
Each emitter artifact is a self-contained jar that depends on claxon-registry
and, where relevant, on one backend SDK.
| Artifact | Class | Behaviour |
|---|---|---|
|
|
Converts tags to CloudWatch |
|
|
Forwards to a non-blocking StatsD client at |
|
|
Registers a |
|
|
Formats each reading as
|
|
|
Discards every reading. Useful as a placeholder when metrics are disabled or during tests. |
|
|
Buffers readings in a |
Single class: EmitterResource, a JAX-RS resource under
/org/smallmind/claxon/emitter/{name}. Looks up the named emitter, verifies
its method is PULL, and returns the result of emit() as an HTTP 200 body.
Pushing emitters accessed through this endpoint raise
InvalidEmitterException; missing ones raise UnknownEmitterException.
Currently ships one feature: ProfileFeature in the jvm sub-package. It
reports fifteen JVM/OS quantities on each collection cycle
(heapMemoryMax, heapMemoryUsed, youngCollectionCount,
youngCollectionTime, processCPUTime, compilationTime, and so on) via a
cluster of helper classes (JVMState, MemoryPools, OSFacts,
GarbageFacts, CompilationAndHeapFacts) that resolve their MXBeans by name
and fall back to zero-valued sentinels when a generational collector is not in
use (e.g. ZGC, Shenandoah). An optional minimumRecordingDelayMilliseconds
throttle has the feature return null (skipping the cycle) when called too
soon after the previous emission.
A handful of terms show up throughout the module and are worth pinning down.
- Meter
-
A stateful object that accepts
update(long value)and produces aQuantity[]when the registry callsrecord(). The instance is keyed by(caller class, tag array)and is constructed lazily from aMeterBuilderon the firstregisterfor that key. - Aggregate
-
The low-level primitive inside a meter (
Tallied,Bounded,Averaged,Paced,Stratified,Pursued,ExponentiallyWeightedMovingAverage). A single aggregate does one job well; a meter composes one or more of them to form a domain-level metric shape. The distinction matters for testing — aggregates are easy to unit-test in isolation — and for performance — aggregates use the most forgiving concurrency primitive that still guarantees no lost updates. - Emitter
-
A consumer of collected readings.
PushEmitter.record(…)is called on every collection interval by the registry’s worker thread for every meter that produced a non-empty reading.PullEmitter.emit()is called by whatever outside consumer wants the current buffer (typically Prometheus scrapingclaxon-http). - Collection stint
-
The interval between successive polls of the meters.
Stint(time, TimeUnit)fromsmallmind-nutsnboltsis used throughout the module to carry scalar-plus-unit durations without losing precision. Default is 2 seconds. - Termination stint
-
The bounded time
stop()waits for the background collection worker to terminate before throwing aTimeoutException. Default is 10 seconds; when set tonullthe registry falls back to five times the collection stint. - Naming strategy
-
The function that maps a caller class to a meter name. The registry asks the strategy exactly once per
(caller, tags)key and caches the answer — including the negative answer — so anullreturn persists as aNoOpMeterentry in thenoopSetfor the life of the registry. Callers that should not be measured can therefore be silenced by the naming strategy alone, with no call-site changes. - Registry tag, meter tag, instance tag
-
Three orthogonal levels of tagging, merged in that order by
ClaxonConfiguration.calculateTags(name, instanceTags…). Registry tags apply to every reading; meter tags apply to every reading from the named meter; instance tags are supplied at each call site. The result is a singleTag[]passed to the emitter, so downstream code does not need to know how it was assembled. - Quantity
-
A single numeric measurement inside a meter. A meter emits several of them per reading (
count,rate,p99, and so on).QuantityType.COUNTvsNONEallows emitters that distinguish counters from gauges (Datadog StatsD, Prometheus) to route each quantity correctly. - Unplugged instrumentation
-
The
UnpluggedInstrumentationreturned byInstrument.with(…)when no registry has been installed, when the calling thread has neither aPerApplicationScopenor aPerApplicationContextbinding, or when neither binding it has holds a registry. All metric-facing methods are no-ops, buton(executable)still runs the executable and propagates its result or exception. That keeps the call-site contract honest even when metrics are disabled.
Artifacts are published under org.smallmind with version
${project.version}.
An application always depends on claxon-registry (plus one or more emitter
artifacts):
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>claxon-registry</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>claxon-emitter-message</artifactId> (1)
<version>${project.version}</version>
</dependency>-
Pick whichever emitter(s) match the backends you want to push to. The artifact ids are
claxon-emitter-aws,claxon-emitter-datadog,claxon-emitter-jmx,claxon-emitter-message,claxon-emitter-noop, andclaxon-emitter-prometheus. Each brings in only its own backend SDK.
| Artifact | Module name |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Optional add-ons:
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>claxon-http</artifactId> (1)
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>claxon-exotic</artifactId> (2)
<version>${project.version}</version>
</dependency>-
Adds
EmitterResourcefor exposing pull emitters (typically Prometheus) over HTTP via JAX-RS. -
Adds
ProfileFeaturefor JVM/OS metrics. The exotic module is weaved with the same AspectJ plugin as the registry, so it can be annotated with@Instrumentedif a caller wants to measure its own sampling cost.
| Artifact | Module name |
|---|---|
|
|
|
|
@Instrumented only works when AspectJ weaves InstrumentedAspect into the
target classes. The project’s parent claxon/pom.xml already configures the
dev.aspectj:aspectj-maven-plugin; inheriting that build section (or adding
it explicitly) is what activates the advice. Without weaving, the annotation
is inert — the method runs normally and no meter is produced.
The woven advice lands in your classes, so your application supplies
org.aspectj:aspectjrt at run time; claxon-registry declares it optional
and does not bring it.
-
claxon-registrypulls inHdrHistogram,jakarta.xml.bind-api,spring-beans,jackson-databind, and the SmallMind support libraries (scribe-pen,smallmind-nutsnbolts, andweb-json-scaffold, which the generated JSON views use at runtime).web-json-doppelgangerandjakarta.annotation-apiare optional dependencies: the registry needs them only to build (the Doppelganger annotations and processor, and the source-retention@Generatedon the generated views), so neither reaches your classpath. -
claxon-emitter-awsbrings in the AWS SDK v2 (cloudwatch,auth,regions,aws-core). -
claxon-emitter-datadogbrings incom.datadoghq:java-dogstatsd-client. -
claxon-emitter-messagebrings inscribe-pen(only needed if you useScribeLoggerConsumer;MessageEmitteritself has no logging dependency). -
claxon-emitter-prometheusandclaxon-emitter-jmxare SDK-free — they only depend onclaxon-registryand, for Prometheus,smallmind-nutsnbolts.
Every Claxon artifact ships an explicit module descriptor under the name in the tables above, exporting all of its packages. On the classpath the descriptors are ignored. See Module Path And Classpath for the repository-wide rules.
For org.smallmind.claxon.registry:
-
It re-exports (
requires transitive)org.smallmind.nutsnbolts,jakarta.xml.bind, andtools.jackson.databind, and requiresorg.smallmind.scribe.pen,org.smallmind.web.json.scaffold, and the automatic modulesspring.beansandHdrHistogram. Automatic modules are never re-exported: a module that uses the Spring factory beans inorg.smallmind.claxon.registry.springalso requiresspring.beans, and one that calls theHistogramTimeconstructor orgetHistogram()also requiresHdrHistogram. That name is derived from the jar’s file name (the HdrHistogram jar declares none), so it changes if the jar is renamed. -
org.aspectj.runtime,org.smallmind.web.json.doppelganger, andjakarta.annotationarerequires static, matching their optional POM dependencies. An application that weaves@Instrumentedrequiresorg.aspectj.runtimeitself. -
It opens
org.smallmind.claxon.registryunconditionally soclasspath:org/smallmind/claxon/registry/claxon.xmlstays loadable from other modules,org.smallmind.claxon.registry.jsontojakarta.xml.bindandtools.jackson.databindfor the generated*InViewclasses the meter parsers read, andorg.smallmind.claxon.registry.springtospring.coreandspring.beans.
For the emitters and add-ons, each re-exports org.smallmind.claxon.registry
(requires transitive), so requiring one artifact is enough to use the
registry API:
-
org.smallmind.claxon.emitter.awsrequires the AWS SDK automatic modules (software.amazon.awssdk.auth,.awscore,.regions,.services.cloudwatch) andspring.beans.AWSEmitter(CloudWatchClient, String)andCloudWatchClientFactory.setRegion(Region)expose SDK types, so a module that calls them requiressoftware.amazon.awssdk.services.cloudwatchandsoftware.amazon.awssdk.regionsitself. It opensorg.smallmind.claxon.emitter.awstospring.coreandspring.beans. -
org.smallmind.claxon.emitter.datadogrequiresjava.dogstatsd.client, a name derived from the jar’s file name (the DogStatsD jar declares none), andspring.beans. It opensorg.smallmind.claxon.emitter.datadog.springtospring.coreandspring.beans. -
org.smallmind.claxon.emitter.jmxandorg.smallmind.claxon.exoticre-exportjava.management;claxon-exoticalso requiresjdk.managementfor thecom.sun.managementbeansOSFactsreads. -
org.smallmind.claxon.emitter.messagere-exportsorg.smallmind.scribe.penand opensorg.smallmind.claxon.emitter.message.springtospring.coreandspring.beans;org.smallmind.claxon.emitter.noopopensorg.smallmind.claxon.emitter.noop.springthe same way. -
org.smallmind.claxon.emitter.prometheusrequiresorg.smallmind.nutsnbolts. -
org.smallmind.claxon.httpre-exportsjakarta.ws.rsand needs noopens:EmitterResourceis public with public constructors and no injected fields. The host follows theweb-jerseymodule-path rules in WEB.adoc. -
A module that uses the Spring factory beans of any of these artifacts requires
spring.beansitself, because automatic modules are never re-exported.
The smallest meaningful Claxon setup is four lines at startup, one line at each call site, and one bound emitter.
import org.smallmind.claxon.registry.ClaxonConfiguration;
import org.smallmind.claxon.registry.ClaxonRegistry;
import org.smallmind.claxon.emitter.message.MessageEmitter;
import org.smallmind.nutsnbolts.context.PerApplicationContext;
public class Startup {
public static void main (String[] args) {
ClaxonRegistry registry = new ClaxonRegistry(new ClaxonConfiguration()); (1)
registry.bind("console", new MessageEmitter()); (2)
new PerApplicationContext(); (3)
registry.initializeInstrumentation(); (4)
}
}-
Constructs a registry with all defaults:
SystemClock, a 2-second collection stint, a 10-second termination stint, no features, no tags, anImpliedNamingStrategywith no prefix map. -
Binds an emitter.
MessageEmitterwithout a consumer prints every reading toSystem.out. -
Attaches a
PerApplicationContextto the thread. The install on the next line writes throughClaxonRegistryManager.register, which throwsMissingPerApplicationContextExceptionon a thread with neither aPerApplicationContextattached nor aPerApplicationScopebound, and a baremainhas neither. Running the install insidescope.run(…)works as well, but then everyInstrument.with(…)call site must run inside that same scope, or on a thread handed it, or it gets anUnpluggedInstrumentation. Containers that already attach a context (WebContextLoaderListener, the Tanuki wrapper) make this line unnecessary. -
Installs the registry in every per-application binding on the thread so that
Instrument.with(…)at a call site can find it. Skip this step and every call site gets anUnpluggedInstrumentation.
|
Note
|
The default |
At each call site:
import org.smallmind.claxon.registry.Instrument;
import org.smallmind.claxon.registry.Tag;
import org.smallmind.claxon.registry.meter.TallyBuilder;
public class RequestHandler {
public void handle (String userId) {
Instrument.with(RequestHandler.class, new TallyBuilder(), (1)
new Tag("userId", userId)) (2)
.update(1); (3)
}
}-
callerdetermines the meter’s name via the registry’s naming strategy. -
Tags are the dimensional metadata attached to every reading from this meter. Tags plus caller form the meter key — two calls with the same tags reuse the same meter; different tag values give you a distinct meter.
-
For a
Tally,update(1)adds 1 to a cumulative counter.
The equivalent XML form uses the factory beans:
<bean id="claxonRegistry" class="org.smallmind.claxon.registry.spring.ClaxonRegistryFactoryBean">
<property name="configuration">
<bean class="org.smallmind.claxon.registry.ClaxonConfiguration">
<property name="collectionStint">
<bean class="org.smallmind.claxon.registry.spring.StintFactoryBean">
<property name="time" value="10"/>
<property name="timeUnit" value="SECONDS"/>
</bean>
</property>
<property name="registryTags">
<list>
<bean class="org.smallmind.claxon.registry.spring.TagFactoryBean">
<property name="key" value="env"/>
<property name="value" value="production"/>
</bean>
</list>
</property>
<property name="namingStrategy">
<bean class="org.smallmind.claxon.registry.ImpliedNamingStrategy">
<property name="prefixMap">
<map>
<entry value="app.request">
<key>
<bean class="org.smallmind.nutsnbolts.util.DotNotation">
<property name="notation" value="com.example.request.*"/>
</bean>
</key>
</entry>
</map>
</property>
</bean>
</property>
</bean>
</property>
<property name="emitterMap">
<map>
<entry key="console">
<bean class="org.smallmind.claxon.emitter.message.MessageEmitter"/>
</entry>
</map>
</property>
</bean>Because ClaxonRegistryFactoryBean calls initializeInstrumentation() inside
afterPropertiesSet, the registry is live as soon as Spring finishes
constructing it. That install goes through ClaxonRegistryManager.register,
so the thread refreshing the context must carry a binding — a
PerApplicationContext attached (WebContextLoaderListener, the Tanuki
wrapper, the testbench foundation) or a PerApplicationScope bound around
the refresh; with neither, the refresh fails with a
BeanCreationException caused by MissingPerApplicationContextException.
Instrumentation.on(…) records the elapsed time around an executable. The
unit is chosen via as(TimeUnit); the default is milliseconds.
import java.util.concurrent.TimeUnit;
import org.smallmind.claxon.registry.Instrument;
import org.smallmind.claxon.registry.Tag;
import org.smallmind.claxon.registry.meter.HistogramBuilder;
public class DatabaseQuery {
public List<Row> run (String sql)
throws Throwable {
return Instrument.with(DatabaseQuery.class, new HistogramBuilder(), (1)
new Tag("table", tableOf(sql)))
.as(TimeUnit.MICROSECONDS) (2)
.on(() -> driver.execute(sql)); (3)
}
}-
A histogram produces
count,rate,min,max,mean, and five default percentiles — the canonical instrumentation for a latency-sensitive operation. -
Override the reporting unit. The wall-to-wall duration is measured in nanoseconds via the registry’s
Clock.monotonicTime()and converted to microseconds before being fed to the meter. -
WithResultExecutable<T>; use the overload without a return type forRunnable-style blocks.
Choose the meter type by what you want the backend to see.
// Cumulative counter — Datadog counter, Prometheus counter, CloudWatch total
Instrument.with(Orders.class, new TallyBuilder()).update(1);
// Throughput — count + rate, where rate is events per window
Instrument.with(Login.class, new TachometerBuilder()).update(0);
// Throughput plus value envelope — adds min/max of the recorded values
Instrument.with(Upload.class, new SpeedometerBuilder()).update(bytes);TachometerBuilder and SpeedometerBuilder default to a 1-second window;
pass .resolution(new Stint(5, TimeUnit.SECONDS)) to change it.
When the value you care about is already tracked by an object you control, use
Instrumentation.track(object, fn) instead of pushing values by hand. The
registry polls the function on every collection interval until the object is
garbage-collected.
import java.util.concurrent.ArrayBlockingQueue;
import org.smallmind.claxon.registry.Instrument;
import org.smallmind.claxon.registry.meter.GaugeBuilder;
public class WorkQueue {
private final ArrayBlockingQueue<Task> queue;
public WorkQueue () {
queue = Instrument.with(WorkQueue.class, new GaugeBuilder()) (1)
.track(new ArrayBlockingQueue<>(1024), (2)
q -> (long)q.size()); (3)
}
}-
GaugeBuilderpicks min/max/average. ATallyBuilderwould give a running total;HistogramBuilderwould give percentiles. -
trackholds aWeakReferenceso it does not prevent the queue from being garbage-collected when the owningWorkQueuegoes away. The method returns the queue unchanged to support fluent assignment. -
The function is sampled once per collection interval (2 seconds by default); it is not called on every queue operation.
@Instrumented turns mechanical timing into a one-line declarative statement.
The parser class picks the meter type; the JSON string configures it.
import java.util.concurrent.TimeUnit;
import org.smallmind.claxon.registry.aop.ConstantTag;
import org.smallmind.claxon.registry.aop.Instrumented;
import org.smallmind.claxon.registry.aop.ParameterTag;
import org.smallmind.claxon.registry.json.HistogramParser;
public class CheckoutService {
@Instrumented(
parser = HistogramParser.class, (1)
json = "{\"percentiles\":[{\"name\":\"p99\",\"value\":99.0}]}", (2)
constants = {@ConstantTag(key = "service", constant = "checkout")}, (3)
parameters = {@ParameterTag(key = "method", parameter = "paymentMethod")},(4)
timeUnit = TimeUnit.MILLISECONDS
)
public Receipt checkout (String userId, String paymentMethod) {
// ... real work ...
}
}-
Any
InstrumentedParserimplementation can be used here, including application-supplied ones. The built-in set isGaugeParser,TallyParser,SpeedometerParser,TachometerParser,HistogramParser,TraceParser. -
JSON configuration for the parser. Fields absent from the JSON retain builder defaults — so
"{}"is always a legal value. -
Constant tags do not vary between calls.
-
Parameter tags are resolved at each invocation.
parametercan be a source-level name (requires-parametersat compile time or an ASM fallback) or a zero-based index string like"1".
A global kill switch:
@Instrumented(parser = GaugeParser.class, active = false)
public void hotPath () { ... }With active = false, the aspect passes through with zero overhead.
Prometheus is a pull model: the emitter buffers, and an external scraper asks
for the current payload. Claxon wires that with PrometheusEmitter plus
EmitterResource:
<bean id="prometheusEmitter" class="org.smallmind.claxon.emitter.prometheus.PrometheusEmitter"/>
<bean id="claxonRegistry" class="org.smallmind.claxon.registry.spring.ClaxonRegistryFactoryBean">
<!-- configuration omitted -->
<property name="emitterMap">
<map>
<entry key="prometheus" value-ref="prometheusEmitter"/> (1)
</map>
</property>
</bean>
<bean id="claxonEmitterResource" class="org.smallmind.claxon.http.EmitterResource"> (2)
<property name="registry" ref="claxonRegistry"/>
</bean>-
The binding key becomes the name in the HTTP path.
-
The JAX-RS resource exposes every pull emitter registered under the given name. Wire it into your JAX-RS runtime the same way you wire any other resource.
A Prometheus scraper that hits /org/smallmind/claxon/emitter/prometheus
receives output like:
com_example_request:count{env="production",userId="42"} 128
com_example_request:rate{env="production",userId="42"} 12.8
# EOFJMXEmitter registers one MeterDynamicMbean per meter+tag combination and
keeps its attributes in sync on every cycle.
import java.lang.management.ManagementFactory;
import org.smallmind.claxon.emitter.jmx.JMXEmitter;
ClaxonRegistry registry = new ClaxonRegistry(configuration);
registry.bind("jmx", new JMXEmitter(ManagementFactory.getPlatformMBeanServer()));
registry.initializeInstrumentation();After this, any metric produced through the registry shows up as a dynamic
MBean with one attribute per Quantity.getName(). ObjectName domains are
the meter names; key-properties are the tags.
DataDogEmitter is push-only (UDP StatsD) and routes QuantityType.COUNT
through StatsDClient.count; everything else goes through gauge.
import org.smallmind.claxon.emitter.datadog.DataDogEmitter;
Emitter emitter = new DataDogEmitter(
"myapp", // prefix
"localhost", // agent host
8125, // UDP port
true); // COUNT-typed quantities as StatsD counters
registry.bind("datadog", emitter);The constructor accepts an optional trailing Tag… constantTags varargs
parameter; the four-argument form above simply omits it.
AWSEmitter takes a pre-built CloudWatchClient and a namespace. For a
Spring application, wire both with CloudWatchClientFactory:
<bean id="cloudWatchClient"
class="org.smallmind.claxon.emitter.aws.CloudWatchClientFactory">
<property name="awsAccessKey" value="${aws.access.key}"/>
<property name="awsSecretKey" value="${aws.secret.key}"/>
<property name="region" value="#{T(software.amazon.awssdk.regions.Region).US_EAST_1}"/>
</bean>
<bean id="awsEmitter" class="org.smallmind.claxon.emitter.aws.AWSEmitter">
<constructor-arg ref="cloudWatchClient"/>
<constructor-arg value="MyApp/Production"/>
</bean>Every collection cycle produces one PutMetricData call per meter+tag
combination, batching all quantities for that meter into a single request.
ProfileFeature plugs into ClaxonConfiguration.setFeatures and runs
alongside normal meters.
import java.util.concurrent.TimeUnit;
import org.smallmind.claxon.exotic.jvm.ProfileFeature;
import org.smallmind.claxon.registry.ClaxonConfiguration;
import org.smallmind.claxon.registry.feature.Feature;
import org.smallmind.nutsnbolts.time.Stint;
ClaxonConfiguration configuration = new ClaxonConfiguration();
configuration.setCollectionStint(new Stint(5, TimeUnit.SECONDS));
configuration.setFeatures(new Feature[] {
new ProfileFeature(
"jvm.profile", // meter name
30_000L, // minimum 30s between emissions
true) // prepend host=<local hostname>
});
ClaxonRegistry registry = new ClaxonRegistry(configuration);The resulting reading carries fifteen quantities per cycle (see the class
Javadoc for the full list) under the meter name jvm.profile, with whatever
registry/meter tags are in effect plus the automatic host tag.
InstrumentedParser is a @FunctionalInterface, so a custom parser can be a
lambda — but @Instrumented needs a Class<? extends InstrumentedParser>
with a no-arg constructor. In practice, custom parsers are tiny concrete
classes:
public class FixedLoadAverageParser implements InstrumentedParser<Trace> {
@Override
public MeterBuilder<Trace> parse (String json) {
return new TraceBuilder()
.windowTimeUnit(TimeUnit.MINUTES)
.windows(new Window[] {new Window("m1", 1), new Window("m30", 30)});
}
}NamingStrategy.from(Class<?>) returns the meter name for the caller or
null to mean "don’t measure this caller". The registry remembers null
answers in an internal noopSet, so a rejected caller is rejected forever
for that tag combination — the strategy is not consulted again.
-
ImpliedNamingStrategy— scans aMap<DotNotation, String>and returns the string associated with the pattern that produces the highest positive match score against the caller’s fully qualified name. An empty or unset map rejects everything. A wildcard key (*notation) is a useful catch-all when you want the strategy to accept every caller but route unknowns to a single "unknown" namespace. -
ObviousNamingStrategy— accepts the caller iff any whitelist pattern matches its name; returns the fully qualified name itself with$replaced by.. Useful when the metric backend already has your package structure and you don’t want to invent a second one.
A typical mixed configuration keeps well-known namespaces under a friendly prefix and everything else under a single bucket:
Map<DotNotation, String> prefixMap = new LinkedHashMap<>();
prefixMap.put(new DotNotation("com.example.request.*"), "app.request");
prefixMap.put(new DotNotation("com.example.db.*"), "app.db");
prefixMap.put(new DotNotation("*"), "app.other");
configuration.setNamingStrategy(new ImpliedNamingStrategy().setPrefixMap(prefixMap));ClaxonConfiguration.calculateTags(name, instanceTags…) produces the final
Tag[] passed to the emitter. It concatenates, in order:
-
registryTags(set on the configuration — applied to every reading). -
The meter-specific tags from
meterTags.get(name)(set on the configuration — applied only when the resolved meter name matches). -
instanceTags(passed at the call site throughInstrument.with(…, tags)).
If all three levels are empty, calculateTags returns null rather than a
zero-length array. That is what lets an emitter distinguish "no tags
configured" from "tag set was explicitly emptied".
The registry keys meters on a composite of (caller class, tag array). Two
registrations with the same caller class but different tag arrays produce
two distinct meters. A typical mistake is to include a high-cardinality
value (a user id, a session id, a UUID) as a tag; because every distinct
value becomes a new meter, the registry’s map grows unboundedly. Use
track(object, fn) for per-object metrics, or accept the cardinality
tradeoff deliberately.
ClaxonRegistry.collect() is scheduled on a single-thread
ScheduledExecutorService with scheduleWithFixedDelay, so it runs once per
collectionStint (measured from the end of the previous pass). Each pass:
-
Calls
measurableTracker.sweepAndUpdate()— drains the weak-reference queue and pushes fresh measurements into every surviving tracked object’s meter. -
For each configured
Feature, callsrecord(); if the result is non-null and non-empty, dispatches it to every bound emitter. -
For each cached meter, calls
record(); if the result is non-null and non-empty, dispatches it to every bound emitter.
Exceptions raised by an individual emitter are caught and logged via
scribe-pen; any other failure of the pass is caught and logged as a whole, so
a single bad collection cannot cancel future runs. stop() calls shutdown()
on the executor and then awaitTermination bounded by the configured
termination stint; if the in-flight pass does not finish within that window,
stop() throws a TimeoutException.
-
ClaxonRegistry,ClaxonConfiguration,MeasurableTracker, and the six built-in meters are safe for concurrent use from any thread. All mutation happens throughConcurrentHashMap,AtomicLong,LongAdder,LongAccumulator,ReentrantLock, or HdrHistogram’sRecorder. -
The
AveragedandExponentiallyWeightedMovingAverageaggregates usetryLock+ overflow queue so writers are non-blocking in the common case; queued values are folded in the next time the lock is available. -
Stratifiedreads are serialised onthis; writes are wait-free on the volatilewriteRecorder. -
Emitters are responsible for their own thread safety. The registry calls
recordfrom its worker thread only, so emitters that don’t maintain external state can rely on single-threaded invocation during the push path.PullEmitterimplementations (e.g.PrometheusEmitter) additionally need to guard the pull path; the built-in Prometheus emitter uses a double-buffer swap plus asynchronized emit(). -
Instrumentis backed byClaxonRegistryManager, which registers into everyPerApplicationScopeorPerApplicationContextbound on the registering thread and resolves scope first, then context — one registry per application. That is the right boundary for OSGi, app-server, and multi-tenant deployments.
-
Pointcut is
(execution || initialization) && @annotation. Both methods and constructors are advisable. -
The parser is instantiated via its public no-arg constructor on every invocation. Parsers that do meaningful work on construction should be cheap, or the overhead will show up on the hot path. The built-in parsers are all trivial.
-
Tag array order is
constantsfirst, thenparameters. If two tags share a key, both are emitted; the emitter decides how to resolve the collision (most backends accept duplicate keys). -
Reflective failures (no-arg constructor missing,
parsethrows, parameter cannot be resolved) surface asInstrumentationException— an unchecked wrapper — rather than as checked exceptions in the caller’s signature.
QuantityType.COUNT is set by meters whose value is a cumulative event
count: Tally.record emits a single count; Tachometer.record and
Speedometer.record emit count; Histogram.record emits count. All
other quantities use QuantityType.NONE. Emitters that distinguish counters
from gauges (Datadog, Prometheus) inspect the type; emitters that don’t
(AWSEmitter, JMXEmitter, MessageEmitter) ignore it.
The Prometheus text exposition format restricts metric and label names to
[a-zA-Z_:]. PrometheusEmitter.mangle(…) normalises the
meter name, quantity name, and tag keys as follows: prepend when the
first character is a digit, insert at every lower-to-upper transition
while lowercasing the uppercase character itself (so httpRequests
becomes http_requests), and substitute every non-alphanumeric character
with _. Tag *values are not mangled, but they are quoted in the output
(label="value").
PrometheusEmitter.record(…) writes to a volatile writeMap; emit() is
synchronized, swaps read and write maps, renders every entry in the new
read map, and clears it. That means a scrape gets only the readings that
arrived between it and the previous scrape. If your scrape interval is
longer than your collection interval, intermediate readings for the same
meter+tag+quantity key overwrite each other; that is by design for a
pull-on-demand backend.
JMXEmitter.record(…) checks server.isRegistered(objectName) and, when
false, grabs the MBeanServer monitor with a double-checked locking pattern
before registering a new MeterDynamicMbean. Unregistration is not
automatic — MBeans linger until the process exits or the registry’s meter
cache is evicted. If your callers produce unbounded tag values, you will
accumulate JMX entries; treat this the same way you would treat any other
high-cardinality-tag issue.
A Feature can return null from record() to skip an interval without
producing a reading. ProfileFeature uses this to cap emission frequency
independently of the registry’s collection stint: set
minimumRecordingDelayMilliseconds to a value larger than the stint, and
the feature will quietly drop cycles in between. The registry treats
null and zero-length arrays equivalently: neither reaches the emitter.
The module distinguishes three broad groups of failure.
- Call-site failures
-
IllegalArgumentExceptionfromnew Tag(key, value)when either component is null or empty — surfaced at startup or when tags are built dynamically. The constructor fails fast; there is no silent coercion. - Registry / configuration failures
-
No dedicated exception type — misconfiguration (missing naming strategy, empty prefix map, forgotten
initializeInstrumentation()call) shows up as "my metrics aren’t appearing". The registry does not throw for these cases; callers ofInstrument.with(…)receive anUnpluggedInstrumentationor aNoOpMeterand keep running. The one install-time exception:initializeInstrumentation()(and soInstrument.register) on a thread with neither aPerApplicationContextattached nor aPerApplicationScopebound throwsMissingPerApplicationContextException. - Emitter failures
-
Emitter implementations may throw any checked or unchecked exception from their
record(…)method — the signature allowsthrows Exceptionso backend-specific exceptions can propagate without wrapping. The registry’s collection worker catches every exception from an emitter, logs it throughscribe-penat ERROR, and continues. The worker thread never exits because an emitter misbehaves. - HTTP endpoint failures
-
EmitterResourceraisesUnknownEmitterExceptionwhen no emitter is bound under the requested name, andInvalidEmitterExceptionwhen the emitter is not of typePULL. Both extendFormattedExceptionso diagnostic context (the missing name or the actual method) can be embedded in the message without a separateString.formatcall at the throw site. Map both to HTTP 404 / 400 in the JAX-RS layer. - AOP failures
-
InstrumentationException(aRuntimeException) wraps reflective or JSON-parse errors from inside the aspect. The advised method itself never sees this exception path — it is raised only when the aspect cannot assemble its metering apparatus.
| Setting | Default | Source |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
empty |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- Registry lifecycle
-
Construct once at startup; call
initializeInstrumentation()before anyInstrument.with(…)call runs. Callstop()during shutdown so the collection worker exits cleanly and any in-flight emitter receives a final flush opportunity.stop()shuts the executor down and waits up to the configured termination stint for the in-flight pass to finish, throwingTimeoutExceptionif it does not; it also propagatesInterruptedExceptionif the caller is interrupted while waiting.ClaxonRegistryFactoryBean.destroy()does this for Spring contexts. - Background thread naming
-
The collection executor’s worker is created through a
ThreadFactorythat names itclaxon-collectionand marks it a daemon, so it appears under that name in thread dumps. - Choosing between push and pull
-
CloudWatch, Datadog, JMX, and the message emitter are push. Prometheus is pull. You can bind several emitters of either kind simultaneously — the collection loop forwards the same readings to all of them. The trade-off is not exclusive.
- High-cardinality tags
-
The registry’s meter map keys on the whole tag array. A tag whose value is effectively unbounded (user id, UUID, incoming URL) will cause unbounded meter creation. If that’s what you want (for example for a small whitelisted set of users), fine — otherwise keep tags coarse.
- Precision of
Stratified -
HdrHistogram allocates memory proportional to
log(highestTrackableValue / lowestDiscernibleValue) * significantDigits. The default[1, 3_600_000]with two digits is a comfortable choice for millisecond latencies. If you record nanosecond values, bumphighestTrackableValueor you’ll overflow. - Prometheus output inclusion in Spring context
-
claxon.xml(underclaxon-registry/src/main/resources/spring/org/smallmind/claxon/registry/) ships an example Spring configuration that declares aclaxonRegistrybean and aclaxonEmitterResourcepointing at it. It is intended as a reference, not a drop-in import — real applications will want to customise the naming strategy, tags, and emitter set rather than inherit the placeholder values in the example.
- Readings never appear in the backend
-
Check, in order: (a) that
registry.initializeInstrumentation()was called — otherwiseInstrument.with(…)returnsUnpluggedInstrumentationand every update is silently discarded; (b) that the recording thread carries a binding whose registry was written — a thread with neither aPerApplicationScopenor aPerApplicationContext, a scope the install never ran inside, or a context attached after the install all makeInstrument.with(…)returnUnpluggedInstrumentationsilently; Claxon logs nothing. The phalanx transports andMockMessageRouter(when constructed) and the quorumComponentPool(when started) adopt the scope bound on that thread if they were given none, so their worker threads record through the registry the install wrote into that scope; (c) that the naming strategy does not returnnullfor the caller class — drop a breakpoint inImpliedNamingStrategy.fromor switch toObviousNamingStrategywith a permissive whitelist to confirm; (d) that at least oneEmitteris bound; (e) that the collection stint has had time to elapse since the first update. - Every caller is measured into the same meter
-
You’ve only mapped
new DotNotation("*")to a single prefix and your callers aren’t providing distinct tags. Either add caller-specific entries to the prefix map, or useObviousNamingStrategyso each class gets its own fully-qualified meter name. IllegalArgumentException: Both key and value must be neither null nor empty-
Raised by
new Tag(key, value). Check the tag construction path — a@ParameterTagwhose parameter resolves tonull, or a SpringTagFactoryBeanwith an unresolved${}placeholder, will hit this. @Instrumentedannotation appears to do nothing-
AspectJ weaving did not run. Inherit the
claxon/pom.xmlbuild section or adddev.aspectj:aspectj-maven-pluginto your build directly, withclaxon-registrylisted as aweaveDependency. Without the weaver,@Instrumentedis just metadata. MeterDynamicMbeanregistrations accumulate in JMX-
You are emitting tags with unbounded values.
JMXEmitternever evicts an MBean once registered; the remedy is to constrain tag cardinality on the call side.ClaxonRegistry.unregister(caller, tags)is available if you need to remove a specific meter (and by extension, trigger JMX cleanup on the next emission of a different-tagged reading from the same caller — the MBean is still there until you restart). - Prometheus scrape output has garbled metric names
-
Your caller name or tag key contains characters outside
[A-Za-z0-9].PrometheusEmitter.mangleconverts them to_; if you want deterministic names, choose a naming strategy whose output is already Prometheus-legal. Histogram.record()returnsNaNforminimum/maximum-
HdrHistogram’s
getMinValueandgetMaxValueproduceLong.MAX_VALUEand0for empty intervals, which cast toDouble.MAX_VALUEand0.0in theQuantity. Treat any minimum/maximum from an interval withcount == 0as an absent measurement, regardless of the numeric value.
- Single-process scope
-
One
ClaxonRegistrycovers one JVM process. Cross-process rollup is the backend’s job. A registry is installed perPerApplicationContext/PerApplicationScopebinding, so each application sharing a JVM can host its own registry, but they do not share state. - Meter eviction
-
The registry evicts a meter only when an application explicitly calls
unregister(caller, tags)or when a tracked object is garbage-collected (viaMeasurableTracker). Meters built for one-off tag values are not reclaimed automatically. - No typed boolean or string tag system for
@Instrumented -
Both
@ConstantTagand@ParameterTagproduce string-valued tags.@ParameterTagcallstoString()on the resolved argument; any complex object is serialised with its defaulttoStringunless you override it. For controlled formatting, use call-siteInstrument.with(…)and construct theTagexplicitly. @Instrumentedparser construction on every call-
The aspect instantiates the parser via reflection on every intercepted call. The built-in parsers are stateless and trivial, but application code that supplies a heavy parser (for example, one that loads configuration from disk) will pay that cost per invocation. Cache externally if the parser does real work.
ProfileFeatureduplicate-entry bug-
In the current
record()implementation, the three memory-pool quantitiesedenMemoryUsed,survivorMemoryUsed, andtenuredMemoryUsedare all sourced fromJVMState.getCompilationTime()instead of the corresponding memory-pool accessors. Treat those three quantities as unreliable until fixed;heapMemoryMax,heapMemoryUsed, and the GC counters are correct. - No built-in rate-limiting or back-pressure on emitters
-
If an emitter is slower than the collection stint, the worker thread blocks on it, deferring the next cycle. Network-bound emitters (CloudWatch, Datadog) should use SDKs that buffer asynchronously — both built-in emitters already do so.
Claxon is a small, opinionated metrics framework made of four moving parts:
a registry that polls on a fixed cadence, a family of meter types composed
out of concurrency-friendly aggregates, a static façade that lets call
sites request instrumentation without holding a registry, and a set of
emitter artifacts that each bind the registry to a specific backend. The
registry is stable across call sites (same (caller, tags) means the same
meter instance), fail-safe at the edges (no registry means
UnpluggedInstrumentation; no name means NoOpMeter), and emitter-agnostic
at the core — a single application can bind JMX, CloudWatch, Prometheus,
and a log stream to the same registry and have every meter reach all of
them on every cycle. Pick the meter type that matches the shape of the
reading, pick the emitter that matches the backend, and leave the
collection loop to take care of the rest.