Chapter 18. Dealing with Concurrency Issues: Race Conditions and Immutable Data

image

Doing two or more things at once is hard. Writing multithreaded code is easy. Writing multithreaded code that works the way you expect can be much harder. In this final chapter, we’re going to show you some of the things that can go wrong when two or more threads are working at the same time. You’ll learn about some of the tools in java.util.concurrent that can help you to write multithreaded code that works correctly. You’ll learn how to create immutable objects (objects that don’t change) that are safe for multiple threads to use. By the end of the chapter, you’ll have a lot of different tools in your toolkit for working with concurrency.

What could possibly go wrong?

At the end of the last chapter we hinted that things may not all be rainbows and sunshine when you’re working with multithreaded code. Well, actually, we did more than hint! We outright said:

Note

“It all comes down to one potentially deadly scenario: two or more threads have access to a single object’s data.”

image

Get Head First Java, 3rd Edition 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.