The optimization of the lock
Lock is a blocking method in nature, which has poor performance compared with lock – free synchronization method. The optimization of locks is only to a certain extent to maximize lock performance: a. Reduce the holding time to lock only code blocks that require synchronization b. Reducing lock granularity Take HashMap as an example to realize its synchronization. It only needs to use mutex synchronization for its GET and set modes to realize its thread-safe C. Lock separation Use read/write lock to distinguish read/write operations d. lock coarsening If there is a code block in the execution period between the two synchronization modules, merge the two synchronization modules, the core idea is to reduce the number of lock acquisition. E. Lock elimination Avoiding lock operations on objects that cannot be shared f. Lock optimization inside VMS: bias lock, mutex lock, and spin lock (default synchronized operations)
- Biased lock: The lock is biased in favor of the thread that currently owns the lock
- Lightweight locks: Lightweight locks are a fast method of locking
- Spin-lock: A mutex that allows only one thread to access the object without putting the caller to sleep.
The procedure for using a lock inside a VM is as follows: Bias lock is used first, then lightweight lock is used when the lock fails, then spin lock is used when the lock fails, then normal lock is used when the lock fails, and then SUSPEND threads at the OS level when the lock fails
ThreadLocal ThreadLocal is used to manage local variables and implement thread synchronization scenarios with variables. If a local variable is accessed by multiple threads, it needs to implement thread synchronization for variables that have data conflicts (data may change).
// only Bank class, Public class Bank{// Use ThreadLocal to manage shared variables private static ThreadLocal<Integer> Account = new ThreadLocal<Integer>(){ @Override protected Integer initialValue(){ return 100; }}; public void save(int money){ account.set(account.get()+money); } public int getAccount(){ return account.get(); }}Copy the code
Threadlocal.set ()// Set the value for thread-safe conditions. Set cannot use a copy of an object (no references can be used, only a new object can be used)