Loading topic
count++ looks like one step but is really three. When another thread can cut in between those steps, updates get lost.5 min readcount++ can break when two threads run it at the same time. That was an atomicity problem. An atomicity problem happens when the steps of one action get mixed up with the steps of another.6 min readcount++, which is an atomicity problem. One thread can also miss a value that another thread wrote, which is a visibility problem. This chapter shows the simplest tool Java gives you to fix5 min readsynchronized. That works, but it is a blunt tool. The whole method becomes locked, even the parts that never touch shared data. The lock is also the object itself (this), so any other code that holds a reference to your object can use the same lock5 min readsynchronized methods and synchronized blocks. This chapter looks at the machinery underneath them. You will learn what a lock really is, which lock each kind of synchronized code uses, and why a thread is allowed to take a lock it already holds.5 min readsynchronized block fixes that, but sometimes a full lock is more than you need. Java has a lighter tool for this problem: the volatile keyword.5 min readsynchronized. That works, but it is heavy for a job as small as adding one to a number. Java has a lighter tool for this. It lives in the package java.util.concurrent.atomic, and its most used class is AtomicInteger.5 min readsynchronized and atomic classes. Most programs keep their data in collections, though: lists, maps, and queues. This chapter covers the collections Java provides that are already safe for many threads to use at once.4 min readvolatile, and atomic classes. Each tool fixes a problem that comes from shared mutable state. This chapter takes a different approach. If the data can never change, those problems do not happen at all.5 min readsynchronized keyword. Java also has a second way to lock: a lock you create as an object and control by calling methods on it. This chapter shows how to use that kind of lock safely, and when you would pick it over synchronized.5 min readsynchronized, volatile, Thread.start(), and join(). Each one fixed a visibility problem, where one thread could not see another thread's write. This chapter explains the single rule that sits behind all of them: the happens-before relationship.4 min readwait, notify, and notifyAll.5 min readvolatile, or atomic classes. This chapter avoids the problem differently. If only one thread can ever reach a piece of data, no other thread can race with it, so the data needs no lock.5 min readsynchronized or ReentrantLock, lets only one thread in at a time. That is safe, but sometimes it is stricter than it needs to be.4 min read