Structured study notes converted from the supplied PDF. The original PDF page images are not included.
ThreadLocal
ThreadLocal provides thread-local variables. A ThreadLocal object maintains a separate value for each thread that accesses it.
- Each thread gets its own copy of the value.
- A thread can access, modify, and remove its own value.
- The complete code executed by a thread can access its corresponding ThreadLocal value.
- It is useful for values such as user ID and transaction ID.
- For a servlet request, a separate transaction ID can be maintained for every request/thread.
- ThreadLocal was introduced in Java 1.2 and enhanced in Java 1.5.
- A thread cannot directly access another thread's ThreadLocal value.
Basic Example
public class ThreadLocalDemo {
public static void main(String[] args) {
ThreadLocal<String> tl = new ThreadLocal<>();
System.out.println(tl.get()); // null
tl.set("Sri Sai");
System.out.println(tl.get()); // Sri Sai
tl.remove();
System.out.println(tl.get()); // null
}
}
initialValue()
initialValue() can provide an initial value for a thread-local variable. After remove(), the value can be initialized again when the thread accesses the variable.
ThreadLocal<String> tl = new ThreadLocal<String>() {
@Override
protected String initialValue() {
return "Vihas";
}
};
System.out.println(tl.get());
tl.set("Sri Sai");
System.out.println(tl.get());
tl.remove();
System.out.println(tl.get());
Important Methods
| Method | Purpose |
|---|---|
| get() | Returns the current thread's value. |
| set(T value) | Sets the current thread's value. |
| remove() | Removes the current thread's value. |
| initialValue() | Supplies the initial value for a thread. |
Thread-specific customer ID
static Integer custId = 0;
ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return custId++;
}
};
public void run() {
System.out.println(
Thread.currentThread().getName()
+ " executing with customer id " + tl.get()
);
}
Each customer thread can therefore maintain a separate customer ID through the ThreadLocal object.
InheritableThreadLocal
Normally, a parent thread's ThreadLocal value is not available to its child thread. When a child thread needs the parent's value, use InheritableThreadLocal.
- It is a child class of ThreadLocal.
- All ThreadLocal methods are available.
- By default, the child receives the parent's value.
- The child's value can be customized by overriding
childValue().
InheritableThreadLocal<String> local =
new InheritableThreadLocal<String>() {
@Override
protected String childValue(String parentValue) {
return "Vihas";
}
};
Example result: the parent can have Datta while the child receives the customized value Vihas.
ThreadGroup
A ThreadGroup groups related threads into a single unit. A thread group can also contain sub-groups.
- Every Java thread belongs to some thread group.
- The main thread belongs to the
maingroup. - The System thread group acts as the root of the thread-group hierarchy.
- System-level threads include Reference Handler, Finalizer, Signal Dispatcher and Attach Listener.
- Grouping threads makes it easier to perform common operations on multiple threads.
Hierarchy
Constructors
ThreadGroup tg = new ThreadGroup("Sai Group");
ThreadGroup child = new ThreadGroup(tg, "Sai-Child Group");
ThreadGroup belongs to java.lang and directly extends Object.
Example
public class ThreadGroupDemo {
public static void main(String[] args) {
ThreadGroup tg = new ThreadGroup("Sai Group");
System.out.println(tg.getParent().getName());
ThreadGroup tg1 =
new ThreadGroup(tg, "Sai-Child Group");
System.out.println(tg1.getParent().getName());
}
}
Useful operations
ThreadGroup provides operations for obtaining active thread counts, active subgroup counts, enumerating threads/groups, getting the group name and parent, setting maximum priority, daemon status and other group-level information.
Creating threads in a group
ThreadGroup g1 = new ThreadGroup("tg");
Thread t1 = new Thread(g1, "Thread1");
Thread t2 = new Thread(g1, "Thread2");
Thread t3 = new Thread(g1, "Thread3");
Thread t4 = new Thread(g1, "Thread4");
java.util.concurrent and Lock
The traditional synchronized keyword has limitations: it does not provide a convenient non-waiting lock attempt, does not provide a maximum waiting time, gives limited control over waiting threads, and cannot easily coordinate locking across multiple methods.
The java.util.concurrent.locks.Lock API provides more control over concurrency.
Important Lock methods
| Method | Meaning |
|---|---|
| lock() | Acquires the lock, waiting if necessary. |
| tryLock() | Attempts to acquire the lock without waiting. |
| tryLock(long, TimeUnit) | Waits only for the specified amount of time. |
| lockInterruptibly() | Waits for the lock but allows interruption while waiting. |
| unlock() | Releases the lock. |
tryLock()
if (lock.tryLock()) {
// perform safe operations
} else {
// perform alternate operations
}
If the lock is unavailable, tryLock() returns false instead of putting the thread into a waiting state.
Timed tryLock
if (lock.tryLock(2, TimeUnit.SECONDS)) {
// lock acquired
} else {
// lock not acquired within 2 seconds
}
lockInterruptibly()
Acquires the lock immediately when available. If it has to wait and the thread is interrupted, it does not acquire the lock.
unlock()
Releases the lock. The current thread must own the lock; otherwise an IllegalMonitorStateException can occur.
ReentrantLock
ReentrantLock is an implementation of the Lock interface. Reentrant means the same thread can acquire the same lock multiple times.
- Each successful
lock()increases the hold count. - Each
unlock()decreases the hold count. - The lock is released when the hold count reaches zero.
- The default fairness policy is
false.
Constructors
ReentrantLock lock1 = new ReentrantLock();
ReentrantLock lock2 = new ReentrantLock(true);
With fairness set to true, the longest-waiting thread gets preference when possible. With false, the order is not guaranteed.
Example
class Display {
ReentrantLock lock = new ReentrantLock(false);
public void wish(String name) {
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print("Good Morning ");
}
System.out.println(name);
} finally {
lock.unlock();
}
}
}
Thread Pool / Executor Framework
Creating a new thread for every job can cause memory and performance problems. A thread pool maintains a group of already-created worker threads that execute submitted jobs.
- Java 1.5 introduced the executor framework.
- The framework is also called the thread-pool framework.
- Tasks can be submitted using
submit(). - The executor should be shut down using
shutdown()when work is finished.
ExecutorService service =
Executors.newFixedThreadPool(3);
service.submit(task);
service.shutdown();
Executor hierarchy
ScheduledExecutorService → ScheduledThreadPoolExecutor
Runnable vs Callable
| Runnable | Callable |
|---|---|
| Older interface (JDK 1.0) | Introduced in Java 5 |
Uses run() | Uses call() |
| Does not return a result | Can return a result |
| Cannot directly throw checked exceptions from run() | Can throw checked exceptions from call() |
Callable example
class MyCallable implements Callable<Integer> {
private int num;
public MyCallable(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= num; i++) {
sum += i;
}
return sum;
}
}
Future
A Future represents the result of an asynchronous computation.
get()retrieves the result and is blocking until the computation completes.isDone()checks whether computation has finished.cancel()attempts to cancel the computation.
ExecutorService service =
Executors.newFixedThreadPool(3);
Future<Integer> future = service.submit(new MyCallable(10));
System.out.println(future.get());
service.shutdown();
For example, the sum of the first 10 numbers is 55, first 20 is 210, first 30 is 465, and first 50 is 1275.
Scheduled Executors
ScheduledExecutorService can schedule tasks to run once after a delay or periodically.
ScheduledFutureis a specialized Future.getDelay()returns the remaining delay.scheduleAtFixedRate()executes tasks at a fixed rate.scheduleWithFixedDelay()schedules the next execution after a fixed delay following completion.
ThreadPoolExecutor
ThreadPoolExecutor is an implementation of ExecutorService that executes submitted tasks using a thread pool.
Main constructor parameters
| Parameter | Purpose |
|---|---|
| corePoolSize | Number of threads to keep in the pool, even when idle. |
| maximumPoolSize | Maximum number of threads allowed in the pool. |
| keepAliveTime | Maximum idle time for excess threads beyond the core size. |
| unit | TimeUnit used for keepAliveTime. |
| workQueue | Queue that holds tasks before execution. |
| threadFactory | Factory used to create new threads. |
| handler | Policy used when execution is blocked because thread/queue capacity is reached. |
Example configuration
ThreadPoolExecutor executor =
new ThreadPoolExecutor(
2,
2,
2,
TimeUnit.MINUTES,
new ArrayBlockingQueue<Runnable>(2, true),
new ThreadPoolExecutor.CallerRunsPolicy()
);
executor.allowCoreThreadTimeOut(true);
Monitoring a ThreadPoolExecutor
The pool can be monitored using methods such as getPoolSize(), getCorePoolSize(), getActiveCount(), getCompletedTaskCount(), getTaskCount(), isShutdown(), and isTerminated().
String.format(
"[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, " +
"isShutdown: %s, isTerminated: %s",
executor.getPoolSize(),
executor.getCorePoolSize(),
executor.getActiveCount(),
executor.getCompletedTaskCount(),
executor.getTaskCount(),
executor.isShutdown(),
executor.isTerminated()
);