Mind Your Resources

Threads are limited resources, and we shouldn’t create them arbitrarily. EnergySource’s replenish method is wasting a thread and limits the number of instances we can create. If more instances created their own threads like that, we’d run into resource availability problems. The replenish operation is short and quick, so it’s an ideal candidate to run in a timer.

We could use a java.util.Timer. For a better throughput, especially if we expect to have a number of instances of EnergySource, it’s better to reuse threads from a thread pool. ScheduledThreadPoolExecutor provides an elegant mechanism to run periodic tasks. We must ensure that the tasks handle their exceptions; otherwise, it would result in suppression of their ...

Get Programming Concurrency on the JVM now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.