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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access