Spotting Concurrency Issues

Let’s learn to identify the perils in shared mutability with an example and see how to fix those problems. We’ll refactor a piece of code that controls a fancy energy source. It allows users to drain energy, and it automatically replenishes the source at regular intervals. Let’s first glance at the code that’s crying for our help:

tamingSharedMutability/originalcode/EnergySource.java
 
//Bad code
 
public​ ​class​ EnergySource {
 
private​ ​final​ ​long​ MAXLEVEL = 100;
 
private​ ​long​ level = MAXLEVEL;
 
private​ ​boolean​ keepRunning = true;
 
 
public​ EnergySource() {
 
new​ ​Thread​(​new​ ​Runnable​() {
 
public​ ​void​ run() { replenish(); }
 
}).start();
 
}
 
 
public​ ​long​ getUnitsAvailable() { ...

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.