Skip to content

🎏 Simple showcases of java concurrency problems, seeing 🙈 is believing 🐵

License

Notifications You must be signed in to change notification settings

oldratlee/fucking-java-concurrency

Repository files navigation

🎏 fucking-java-concurrency

Github Workflow Build Status Java support License GitHub Stars GitHub Forks GitHub Contributors GitHub repo size gitpod: Ready to Code


📖 English Documentation |📖 tiếng Trung hồ sơ

Simple showcases ofJavaconcurrency problems, seeing 🙈 is believing 🐵.

🍎 Reasons to organize Demo

  • The actual phenomenon that can be observed 🙈 is more intuitive and more trustworthy than the concurrency principle mentioned 🙊.
  • TheJavalanguage standard library supports threads, multithreading is heavily used in the language itself (such asGC) and applications (the server side).
  • Concurrency program design, in the analysis and implementation, the complexity is greatly increased. If you do not fully understand and systematically analyze the concurrent logic, and write code at will, it is not an exaggeration to describe such a program as "accidentally"running with the correct result.
    • The demos here do not give explanations and discussions, and they are all entry-level:neckbeard:.For more information, please loop up the concurrency materials by yourself.

Examples of concurrency problems you encountered in development are welcome to provide (submit Issue) or share (pull request after Fork)! 😘



🍺 Update without synchronization cannot be read in another thread

Demo classNoPublishDemo.

Demo description

Set the fieldstoptotruein themainthread to control the exit of the task thread started inmain.

Problem statement

After themainthread fieldstopistrue,the task thread continues to run, that is, no new value has been read in the task thread.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.NoPublishDemo

🍺 Infinite loop ofHashMap

This problem has been explained in many places.

The Demo classHashMapHangDemocan reproduce this problem.

Demo description

Two task threads are opened in the main thread to perform the put operation ofHashMap.The main thread does the get operation.

Problem statement

The main thread Block is determined by no continuous output, that is, the endless loop ofHashMapappears.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.HashMapHangDemo

🍺 Combined state read invalid combination

When programming, multiple state records will be required (state can be aPOJOobject orints, etc.).

It is often seen that the multi-state read and write code is not synchronized, and the person who write it will naturally ignore the issue of thread safety.

Invalid combinations are combinations that have never been set.

Demo description

The main thread modifies multiple states. For the convenience of checking, each write has a fixed relationship: the second state is twice the value of the first state. Read multiple states in a task thread. Demo classInvalidCombinationStateDemo.

Problem statement

The second state read in the task thread is not twice the value of the first state, that is, an invalid value.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.InvalidCombinationStateDemo

🍺longvariable read invalid value

An invalid value is a value that has never been set.

Reading and writing oflongvariables is not atomic and will be divided into two 4-byte operations.

Demo classInvalidLongDemo.

Demo description

The main thread modifies the long variable. For the convenience of checking, the upper 4 bytes and the lower 4 bytes of the long value written each time are the same. Read the long variable in the task thread.

Problem statement

In the task thread, a long variable whose upper 4 bytes and lower 4 bytes are different is read, which is an invalid value.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.InvalidLongDemo

🍺 the result of concurrency count without synchronization is wrong

Demo classWrongCounterDemo.

Demo description

Two task threads are opened in the main thread to execute concurrent incrementing counts. Main thread final result check.

Problem statement

The count value is incorrect.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.WrongCounterDemo

🍺 Synchronization on mutable fields

It is common to see synchronization code on a volatile field, and the person who write it will naturally feel that this is safe and correct.
# For problem analysis, see the articleSynchronization on mutable fields.

Demo classSynchronizationOnMutableFieldDemo.

Demo description

Two task threads are opened in the main thread to executeaddListener.Main thread final result check.

Problem statement

The final count of Listeners is incorrect.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.SynchronizationOnMutableFieldDemo

🍺 Deadlock caused by the symmetric locks

# For problem analysis, see the articleSynchronization on mutable fields

Demo classSymmetricLockDeadlockDemo.

Demo description

Two task threads are opened in the main thread for execution.

Problem statement

Task thread deadlocked.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.SymmetricLockDeadlockDemo

🍺 Livelock caused by reentrant locks

# For a problem description, see the paragraph about livelocksin this article

Demo classReentrantLockLivelockDemo.

Demo description

Two task threads are trying to acquire a lock that the other thread holds while holding their own lock.

Problem statement

While the threads are releasing their own lock constantly, they are also re-locking it immediately, denying the other thread a chance to acquire both locks. Since both threads are not blocked from executing but blocked from doing meaningful work, this is a livelock.

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.ReentrantLockLivelockDemo

🍺 Instruction reordering causes non-final field variable read error

Demo classFinalInitialDemo.

Demo description

The writer thread calls the constructor of the class, and the reader thread obtains the member variables of the non-final domain of the class.

Problem statement

When calling the constructor, instruction reordering may occur, placing non-final domain variables outside the constructor, causing the writer and reader threads to obtain the default initial values of the variables.(Instruction ordering does not necessarily occur and requires specific hardware and JVM environments).

Quickly run

./mvnw compile exec:java -Dexec.mainClass=fucking.concurrency.demo.FinalInitialDemo