Multi-threaded high-concurrency thread security problem solution

Solving high-concurrency thread security issues generally needs to be handled according to actual business logic. Talking about technology out of business is just hooliganism. For example, there is a scenario: design a ticket grabbing program, and 1,000 people want to grab 100 tickets at the same time. First of all, we have to consider how to design this scenario. If you are using a stand-alone version of the multi-threaded solution, then use the synchronized modification method or lock to ensure the execution order of the threads when accessing the database layer during ticket grabbing; if you are designing a high-availability cluster deployment If you add a multi-threaded solution, you need to use distributed locks to ensure thread safety. Generally, redis-based distributed locks are commonly used. You can also use database-based distributed locks and Zookeeper-based distributed locks.

The stand-alone version uses synchronized or lock:

The synchronized keyword can be used to modify instance methods , static methods, and code blocks of a class.

for example:

public class Counter {
	private int count;
	public synchronized void incr() {
		count++;
	}
	public synchronized int getCount() {
		return count;
	}
}
 

Counter is a simple counter class. After adding synchronized, the code in the method becomes an atomic operation (execute it together if you want to execute it, or not execute it if you don’t execute it). When multiple threads update the same Counter object concurrently, Can't go wrong either.

Similarly, after using the lock , the code block can be executed in the specified order, and the locked code has been accessed by one of the threads, so the other thread can only wait:

private object o = new object();//创建一个对象
public void Work()
{
  lock(o)//锁住这个对象
  {
    //做一些必须按照顺序做的事情
  }
}

High availability cluster deployment uses redis distributed locks:

Redis command description:

(1) setnx command: set if not exists, if and only if the key does not exist, set the value of the key to value. If the given key already exists, SETNX does nothing.

Return 1, indicating that the process has acquired the lock, set the value of key to value
and return 0, indicating that other processes have acquired the lock, and the process cannot enter the critical section.
Command format: setnx lock.key lock.value

(2) get command: Get the value of the key, if it exists, it will return; if it does not exist, it will return nil

Command format: get lock.key

(3) getset command: This method is atomic, setting the value of newValue to the key, and returning the original old value of the key.

Command format: getset lock.key newValue

(4) del command: delete the key specified in redis

Command format: del lock.key
 

Guess you like

Origin blog.csdn.net/lwpoor123/article/details/130218061