Interview Q&A · Java · 5 questions in this topic

Thread Groups, ThreadLocal and Daemon Threads — Java Interview Q&A

All Java topics

How thread groups, ThreadLocal variables, and daemon threads fit into real Java programs. Part of Threads & Concurrency · 294 questions in the Java bank.

What are thread groups?

Answer

A ThreadGroup is a legacy container that groups related threads for bulk operations such as listing or setting default handling. It dates from early Java security designs and offers little control by modern standards. New code should use executors with named thread factories instead, which give better pooling, error handling, and lifecycle control. Know thread groups for completeness, but do not use them in new designs.

What are thread-local variables?

Answer

A ThreadLocal variable gives each thread its own independent copy of a value. Threads can share the ThreadLocal object itself but still see different values when they call get and set. Common uses include per-thread formatters, transactions, and request context that should not be shared. Always call remove when a pooled thread finishes with its copy, otherwise the value can leak across reused threads.

Example

Example.javajava
private static final ThreadLocal<Integer> counter = ThreadLocal.withInitial(() -> 0);
counter.set(counter.get() + 1);
System.out.println("count: " + counter.get());
counter.remove();

What are daemon threads?

Answer

Daemon threads are background service threads that do not keep the JVM alive. The JVM exits once all remaining threads are daemons, even if those daemons are still running. Typical examples are garbage collector threads, timer threads, and housekeeping tasks. Application work that must complete should run on non-daemon user threads instead.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits