DEV Community

ChelseaLiu0822
ChelseaLiu0822

Posted on

shared model

critical section

Multiple threads access shared resources, and when instructions are interleaved during read and write operations on shared resources, concurrent problems may occur.
question
If there are multi-threaded read and write operations on shared resources within a code block, this code is called a critical section.

race condition

Multiple threads are executing in the critical section. Due to the different execution sequences of the code, it is impossible to predict, which is called a race.
state conditions

Methods to avoid race conditions in critical sections:

Blocking solutions: synchronized, lock
Non-blocking solution: atomic variables

synchronized

The object in synchronized can be imagined as a room with only one entrance, and only one person can enter at a time.
Make calculations
When the t1 thread owns the lock and enters the room for calculation, and the context switch occurs, when t2 wants to enter the room, it finds that there is no thread.
If you have a key and cannot enter, it will become blocked (blocked state), and t1 will continue to perform calculations, and only t1 will be released.
After locking, t2 can get the lock and enter the room for calculation.
synchronized actually uses object locks to ensure the atomicity of the critical section code. The code in the critical section is not exposed to the outside world.
Divisible and will not be interrupted by thread switching
Synchronized on member methods lock this object
Synchronized on static methods locks class objects
Member variables and static variables need to consider thread safety when they are shared and have read and write operations.
If the reference object of a local variable escapes the scope of the method, thread safety needs to be considered.

Thread safety class

String
Integer all wrapper classes
StringBuffer
Random
Vector
Hashtable
Classes under the java.until.concurrent package
When multiple threads call a method of their same instance, it is thread-safe, and each of their methods is Atomic, but their combination method is not necessarily atomic.

String and Integer are both immutable classes because their internal state cannot be changed, so their methods are Thread safe

Top comments (0)