"Java Concurrent Programming Practice" Study Notes Chapter 2 Thread Safety

1. What is thread safety

When multiple threads access a class, no matter what scheduling method the runtime environment adopts or how the current threads will be executed alternately, and in the main call generation

The code does not need any additional synchronization or coordination, the class can exhibit the correct behavior, then the class is thread-safe.

The necessary synchronization mechanism is encapsulated in a thread-safe class, so the caller does not need to take further synchronization measures.

Stateless objects must be thread-safe.

 

2. Race conditions

When programming concurrently, incorrect results can occur due to improper execution timing.

For example, check first and then execute.

 

3. Locking mechanism

To maintain state consistency, all state variables need to be updated in a single atomic operation.

 

3.1 Built-in lock

     Java provides a built-in locking mechanism to support atomicity, that is, synchronized code blocks, using synchronized modification, synchronized modification methods, the entire method is a synchronized code block.

 

Synchronized code block:

 

synchronized (lock){
    // access or modify the shared state protected by the lock
}
 

 

Synchronization method:

/**
* Entire method as synchronized code block
*/
synchronized void function1() {
}

 

 

Using synchronized locking for the entire method, and only one thread can execute the method at the same time, will reduce the execution performance, so in general, try not to lock the entire method, but use a smaller synchronized code block.

 

3.2 Reentrancy

     Reentrancy means that a thread can repeatedly acquire the lock it already holds without blocking, that is, the granularity of acquiring the lock is "thread".

 

4. Protect the state with a lock

     For a mutable state variable that may be accessed by multiple threads at the same time, it is necessary to hold the same lock when accessing it, that is, the state variable is protected by this lock.

     For an immutability condition involving multiple variables, all variables involved are protected by the same lock.

 

5. Activity and performance

    In general, there is a mutual constraint between simplicity and performance, and when implementing a synchronization strategy, you must not blindly sacrifice simplicity for performance (which may break security).

     Never hold locks when performing long computations or operations that may not be completed quickly (eg, network or console I/O, database queries, etc.)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326182169&siteId=291194637