Loading topic
count++ is not one step. The other part was that one thread might not see what another thread wrote. Java gives you a simple tool that fixes both problems at once: the synchronized keyword.2 min readsynchronized. That works, but it locks the entire method body. Often only one or two lines touch shared data. A synchronized block lets you lock just those lines.2 min readsynchronized on methods and blocks. This chapter looks at what happens inside the lock that synchronized uses.2 min readvolatile keyword fixes visibility, and it does so without a lock.2 min readcount++ is not one step. It reads the value, adds one, and writes it back. Two threads can mix up those steps and lose updates. A synchronized method fixes this, but it uses a lock for one tiny operation.2 min readList or a Map. The usual ones, such as HashMap and ArrayList, are not thread-safe. Thread-safe means the code works correctly even when many threads use it at the same time. If two threads change a HashMap together, entries can be lo2 min readsynchronized protects shared data. Java also gives you a lock you can hold and control in your own code. It is called ReentrantLock, and it lives in the package java.util.concurrent.locks.2 min readwait, notify, and notifyAll2 min readvolatile, and atomic classes. There is also a simpler option: don't share the data. If only one thread can ever reach an object, no other thread can interfere with it, and you need no synchronization.2 min read