Category Archives: Concurrency Programming

Bad Things Happen – Recognizing Common Pitfalls in Java Concurrency Programming

The rules in concurrency programming are different. Single threaded code is easily understood as deterministic. However, deterministic rules can change when multiple threads are reading and writing to the same memory space. It has been my experience that these rules for writing deterministic thread-safe code are often misunderstood. Bad things that we never expect to happen, happen.

Concurrency programming is mostly about ensuring that your system remains deterministic when multiple threads read and write to the same memory space.

Introductory Concurrency Problem

Let’s take one of the simplest concurrency problems and I will describe what can go wrong.

Let’s say that there exist an Account object in memory with a balance of $500.00, and two threads are reading and writing to it. Thread 1 wants to add $25000 to the balance. Thread 2 wants to withdraw $300 from the balance. If the code is not thread safe, then it will be quite possible for an execution of this scenario to yield a balance of $200.00.

Continue reading