Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Your shared libraries start background threads for metrics flushing, configuration refresh and connection cleanup in every service that uses them. Some services hang at shutdown and others lose final metrics. Define lifecycle standards for library-owned threads.

Library threads must have an explicit lifecycle owned by the application: start them from a start method or a framework hook, never from a static initializer or constructor, and stop them through a close or stop method that Spring calls through SmartLifecycle or a destroy method, flushing final data within a time limit. Use daemon threads only for work that may be abandoned, name every thread with the library's prefix, and prove startup and shutdown behaviour, including timing, in an integration test.

Background to this question

Shared libraries multiply mistakes. One badly behaved background thread inside a metrics client ends up in fifty services, and each team sees a different symptom: one service never exits, another loses its last minute of metrics on every deploy. A senior engineer is expected to turn these symptoms into a standard that all library authors follow. In this answer, we will look at why the two symptoms happen, then set the standard rule by rule: when threads start, how they stop, when daemon threads are acceptable, how threads are named, and how the behaviour is tested.

1Why Services Hang and Why Metrics Get Lost

The two symptoms are mirror images of the same missing lifecycle. A service hangs at shutdown when a library started a non-daemon thread, a thread that keeps the JVM alive, and nothing ever tells it to stop. The application context closes, the main work is finished, and the JVM waits forever for a connection-cleanup loop that runs while(true).

Final metrics are lost when the library took the opposite shortcut and made its flushing thread a daemon. The JVM does not wait for daemon threads, so when shutdown arrives the thread is abandoned in the middle of a sleep, and the last interval of metrics in its buffer is never sent. Neither library offered the application a way to say we are shutting down now, please finish properly.

2Rule 1: Start Threads Explicitly, Never as a Side Effect

A thread started in a static initializer or a constructor starts the moment the class is loaded or an object is built, which may be in a unit test, a CLI tool or a code path that never meant to use the feature. The application cannot control it, cannot configure it first and cannot stop it, because it never got a handle. So the standard is that a library exposes an object with a start() method (or starts work only when the framework starts it) and a matching stop.

Java
// Not allowed: a thread starts when the class loads
public final class MetricsClient {
private static final Thread FLUSHER = new Thread(MetricsClient::flushLoop);
static { FLUSHER.start(); }
}
// Standard: the application owns the lifecycle
public final class MetricsClient implements AutoCloseable {
private final ScheduledExecutorService scheduler;
private volatile boolean started;
public MetricsClient(MetricsConfig cfg) {
this.scheduler = Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().name("acme-metrics-flush-", 0).daemon(false).factory());
}
public void start() {
scheduler.scheduleAtFixedRate(this::flushSafely, 10, 10, TimeUnit.SECONDS);
started = true;
}
@Override public void close() { // stop: flush once more, bounded
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) scheduler.shutdownNow();
flushWithTimeout(Duration.ofSeconds(5));
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
}
}

Notice the time limits on close(). A shutdown that waits forever for an unreachable metrics backend just moves the hang into the library. The standard should give each library a default budget, for example 5 seconds, that the application can configure.

3Rule 2: Integrate With the Spring Lifecycle

Most of our services run on Spring Boot, so the library's starter should register the client as a bean whose lifecycle Spring drives. For simple cases a destroy method is enough: Spring calls close() on AutoCloseable beans when the context closes. For ordering, SmartLifecycle is better. It has start(), stop(Runnable callback) and getPhase(), and Spring starts beans in increasing phase order and stops them in reverse.

Java
@Bean
SmartLifecycle metricsLifecycle(MetricsClient client) {
return new SmartLifecycle() {
private volatile boolean running;
public void start() { client.start(); running = true; }
public void stop() { client.close(); running = false; }
public boolean isRunning() { return running; }
public int getPhase() { return Integer.MAX_VALUE - 100; } // stop early, flush while the app still works
};
}
Step throughOrderly shutdown of a service
KubernetesSpring contextWeb serverMetrics clientPool cleanup
SIGTERM
stop accepting requests, drain
stop(): final flush, max 5 s
flushed
close(): stop cleanup thread
stopped
JVM exits, no threads left

7 messages in order. Play them, or step through them one at a time.

Each library thread stops at a known point, inside a time budget.

The phase matters. Metrics should flush while the HTTP client and the connection pools they depend on are still running, so the metrics bean stops early in the shutdown order. Spring Boot also bounds each stop phase with spring.lifecycle.timeout-per-shutdown-phase, 30 seconds by default, so a misbehaving library cannot block shutdown forever. In Kubernetes, the whole sequence must fit inside the pod's termination grace period.

4Rule 3: Daemon Only for Work That May Be Abandoned

The daemon decision should be written down per thread, not left to defaults. A configuration-refresh poller can be a daemon: if it is cut off at exit, nothing is lost. A metrics flusher or anything that holds buffered data must be non-daemon and must be stopped through the lifecycle, so it gets the chance to flush. And a non-daemon thread is only acceptable if the library guarantees it ends when stop() is called; otherwise the service hangs. Put simply, the daemon flag is a fallback for work we do not care about, never a substitute for shutting down.

Thread rules for the three library features
FeatureDaemon?On shutdown
Metrics flushingNoFinal flush within 5 s, then stop
Configuration refreshYes, may be abandonedCancel the schedule, no flush needed
Connection cleanupNoClose idle connections, stop within 5 s
The daemon flag records whether losing the work is acceptable.

5Rule 4: Name Every Thread With the Library Prefix

Each thread a library creates should carry a prefix such as acme-metrics-flush-1 or acme-config-refresh-1. When a service hangs, a thread dump (jstack or jcmd Thread.print) shows the threads still alive, and with good names the owner is obvious in seconds instead of being pool-3-thread-1. The same names appear in logs, profilers and thread-count metrics. Libraries should accept a ThreadFactory or executor from the application where reasonable, and default to a named factory otherwise.

6Rule 5: Test Startup and Shutdown, Including Timing

A standard only holds if a test enforces it. Each library ships an integration test that starts a Spring context with the starter, closes it, and then asserts that no thread with the library's prefix is still alive and that the close took less than the budget. A second test points the client at a backend that never answers, to prove the shutdown time limit works.

Java
@Test
void contextCloseStopsAllLibraryThreads() {
var ctx = new SpringApplicationBuilder(TestApp.class).run();
long t0 = System.nanoTime();
ctx.close();
long ms = (System.nanoTime() - t0) / 1_000_000;
assertThat(ms).isLessThan(6_000); // within the 5 s budget plus margin
assertThat(Thread.getAllStackTraces().keySet())
.noneMatch(t -> t.getName().startsWith("acme-") && t.isAlive());
assertThat(fakeBackend.receivedFinalFlush()).isTrue(); // last metrics were sent
}

So the standard covers the code, the framework integration and the proof, and each team gets it by depending on the starter instead of reimplementing it.

7Follow-up questions

Why not just call System.exit() to avoid the hang?

It hides the bug and makes things worse for the flushing case. System.exit() still waits for shutdown hooks, and it cuts off any non-daemon work without the orderly stop, so data that should have been flushed is lost. The thread that blocks exit needs a stop method.

What about libraries used outside Spring?

The library itself must still work on its own: start() and close() on a plain object, AutoCloseable so try-with-resources works. Spring integration is a thin starter around that, never the only way to stop the threads.

Should a library register its own JVM shutdown hook?

Only as a last-resort safety net. Hooks run in no defined order and at the same time as each other, so a library cannot know whether its dependencies are still working. Letting the application's lifecycle stop it, in a known order, is more reliable.

8Conclusion

In this answer, we traced both symptoms to missing lifecycle: a non-daemon thread that nobody stops makes the service hang, and a daemon thread that holds data loses it at exit. The standard we set is to start threads explicitly, never in static initializers or constructors, to stop them through close() and Spring's SmartLifecycle with a bounded flush, to use daemon threads only for abandonable work, to name threads with the library prefix, and to prove the behaviour with an integration test that checks remaining threads and shutdown time.

What to say in the interviewAbout 80 seconds aloud

Open with

Both symptoms come from library threads that have no lifecycle the application controls. Services hang because a library started a non-daemon thread that nobody ever stops, and metrics are lost because another library made its flusher a daemon, so the JVM abandons it at exit with data still in the buffer.

Then, if they want more

The standard I'd set has five parts. First, no thread starts in a static initializer or constructor; a library exposes a start method, or starts when the framework starts it.

Second, every library has a stop path, a close method that's also AutoCloseable, and a Spring starter that wires it into SmartLifecycle so Spring stops it in a known phase, with a final flush bounded by a timeout, say five seconds, that fits inside Spring's shutdown phase timeout and the Kubernetes grace period.

Third, daemon threads only for work that can be dropped, like configuration polling; anything holding data is non-daemon and stopped properly. Fourth, every thread is named with the library prefix, like acme-metrics-flush-1, so a thread dump shows the owner immediately.

Fifth, each library ships an integration test that starts and closes a context, then asserts no prefixed threads are alive, the close finished within budget and the final flush happened, including a case where the backend doesn't answer.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your shared libraries start background threads for metrics flushing, configuration...": https://scrivio-interview-library.netlify.app/java/threads/33db5794c5/