Interview Q&A · Java · 5 questions in this topic
Thread Groups, ThreadLocal and Daemon Threads — Java Interview Q&A
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
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.
How is a thread made daemon?
Answer
You mark a thread as daemon by calling setDaemon with true before the thread starts. The daemon status is fixed at start time and is inherited from the creating thread by default. Calling setDaemon after start throws IllegalThreadStateException. The standard pattern is therefore to configure daemon status immediately after construction and before start.
Example
Thread t = new Thread(() -> System.out.println("service")); t.setDaemon(true); t.start();
Can the main thread be made daemon?
Answer
In practice, no, because the main thread is already running when your program gains control. Calling setDaemon on a running thread throws IllegalThreadStateException, and the main thread is no exception. The JVM starts the main thread as a non-daemon user thread so the application stays alive. If you need daemon behaviour, create a new daemon thread instead of trying to convert main.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission