A little bit about distributed locks

      In fact, many people have encountered interviewers during the interview process and asked about distributed implementation? In fact, to answer this question, even if you have never been a distributed lock, as long as you can correctly understand the concept of lock, you can actually answer it. When it comes to application development, it is mainly a matter of thinking. Next we come to unlock first.

     A lock is a shared resource and is mainly used in a multithreaded environment. So why are there locks? Locks are mainly to solve the problem that certain resources can be correctly accessed or modified in a concurrent environment to ensure the correctness of data. In the database, locks are called in different ways, such as: optimistic locks (logical locks, implemented by numerical values), pessimistic locks (database locks); shared locks (select with high concurrency), exclusive locks (update, delete); row-level locks, table locks. The emergence of these locks has a common feature, that is, granularity. Because locks can bring bottlenecks to the system, you should pay attention to such problems in the process of designing applications. So in JAVA, in fact, the design ideas of many locks are very similar to those of databases, such as: read locks (in fact, even shared locks), write locks (exclusive locks); and ConcurrentHashMap uses segmented locks (equivalent to database rows). level lock).

     Okay, so much nonsense. So in a distributed system, if we want to design a distributed lock, what should we do? If each node in the distributed system is regarded as a thread, then everyone should be able to think of how to do it. All we have to do is to find a global shared resource, such as: redis, database, zookeeper, etc., but there is a premise that these resources have only one master. That is to say, even if there are multiple nodes for these shared resources, only one node is the master node, and all data is based on this master node. As long as the lock is placed in such a resource, and all business nodes use the lock according to certain rules, it can be guaranteed that the same lock can only be used by one business node at any time.

Guess you like

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