Many small partners in the learning of Java, always feel that Java multithreading in the actual business is seldom used, so that it will not spend too much time to learn, technical debt constantly accumulated! Until a certain degree of time for the Java multithreading related things are difficult to understand, today we need to explore the same thing and Java multithreading related!
Learn Java Multi-threading should know what is a lock, did not learn to worry about, Java locks can be easily understood as a multi-threaded case access to critical resources of a thread synchronization mechanism.
In the process of learning or using Java, the process encounters a variety of lock concepts: Fair lock, unfair lock, spin lock, reentrant lock, biased lock, lightweight lock, heavyweight lock, read-write lock, mutex, etc.
Are you blindfolded? It doesn't matter! Even if you do not matter, because this and today to discuss the relationship is not very small, but if you as a love to learn the little partner, here also prepared a cheat: "Java Multithreading core Technology", a total of 19 wish you a helping hand!
Java multithreaded Programming core Technology 19 articles
First, why to use the distributed lock
When we develop the application, if we need to do multi-threaded simultaneous access to a shared variable, we can use our learned Java Multi-threading 18-like martial arts for processing, and can run flawlessly, without bug!
Note that this is a stand-alone application, where all requests are assigned to the current server's JVM and mapped to the operating system's threads for processing! This shared variable is just a memory space inside the JVM!
Later business development, need to do a cluster, an application needs to deploy to several machines and then do load balancing, roughly like:
As you can see, the variable a exists in JVM1, JVM2, JVM3 three JVM memory (this variable a mainly manifests as a member variable in a class, is a stateful object, such as a member variable of an shaping type in the Usercontroller controller), If there is no control, variable a also allocates a chunk of memory to the JVM, and three requests are sent over the same variable, obviously the result is wrong! Even if not at the same time, three requests to operate three different JVM memory areas of the data, there is no sharing between variable a, nor visibility, the result is not correct!
If this scenario does exist in our business, we need a way to solve this problem!
To ensure that a method or property can only be executed at the same time in a high-concurrency scenario, you can use Java concurrency-related APIs (such as Reentrantlock or synchronized) for mutually exclusive control in the case of a single-machine deployment of a traditional monomer application. www.shashuiyule.cn in a standalone environment, Java provides a number of concurrent processing-related APIs. However, with the development of the business, the original single-machine deployment system has been evolved into a distributed cluster system, because the distributed system multithreading, multi-process and distributed on different machines, which will make the original single-machine deployment in the case of the concurrency control lock policy failure, simple Java API does not provide the ability of distributed locks. In order to solve this problem, we need a mutual exclusion mechanism across the JVM to control the access of shared resources, which is the problem of distributed lock!
Second, the distribution of the lock should have what conditions
Before analyzing the three implementations of distributed locks, let's look at what the distributed locks should look for:
1, in the Distributed system environment, a method can only be executed by one thread of a machine at the same time;
2, high availability of access to lock and release lock;
3, high-performance acquisition lock and release lock;
4, with reentrant characteristics;
5, with lock failure mechanism, to prevent deadlock;
6, has the non-blocking lock characteristic, namely does not obtain to the lock to return the www.ctxpty.com directly to obtain the lock failure.
Three, three kinds of realization mode of distributed lock
At present, almost a lot of large-scale Web sites and applications are distributed deployment, data consistency in distributed scenarios has always been a relatively important topic. The distributed Cap theory tells us that "none of the distributed systems can meet both consistency (consistency), availability (availability), and partition fault tolerance (Partition tolerance) at most, at the same time." "So many systems will have to make a choice at the beginning of the design. In the vast majority of the Internet scene, the need to sacrifice strong consistency in exchange for the high availability of the system, often only need to ensure "final consistency", as long as the final time is acceptable to the user within the scope.
In many scenarios, in order to ensure the final consistency of the data, www.hjshidpt.com need a lot of technical solutions to support, such as distributed transactions, distributed locks and so on. Sometimes, we need to make sure that a method can only be executed by the same thread at the same time.
Implement distributed lock based on database;
Implement distributed locks based on cache (Redis, etc.);
Implement distributed lock based on zookeeper;
Although there are three kinds of programs, but different business also to choose according to their own situation, they do not have the best only more suitable!
Iv. database-based approach to implementation
The core idea of database-based implementation is to create a table in the database that contains fields such as the method name, create a unique index on the method name field, want to execute a method, insert data into the table using the method name, insert the lock successfully, and delete the corresponding row data release lock when the execution is complete.
(1) Create a table:
(2) To execute a method, insert the data into the table using this method name:
Because we have a unique constraint on the method_name, if there are multiple requests to the database at the same time, the database will ensure that only one operation succeeds, then we can assume that the successful operation of the thread obtains the lock of the method, can execute the method body content.
(3) A successful insert acquires the lock and deletes the corresponding row data release lock when the execution is completed:
Note: This is just a database-based approach that uses a database to implement distributed locks with a lot of other gameplay!
Using database-based implementations is simple, but there are some issues that need to be addressed and optimized for the conditions that a distributed lock should have:
1, because it is based on database implementation, database availability and performance will directly affect the availability and performance of distributed locks, therefore, the database needs to be dual-machine deployment, data synchronization, primary and standby switching;
2, there is no reentrant feature, because the same thread before releasing the lock, the row data has been present, unable to successfully insert the data again, so you need to add a column in the table to record the current acquisition of the lock machine and thread information, when the lock is acquired again, Query the table in the machine and thread information is the same as the current machine and thread, if the same is directly acquired lock;
3, there is no lock failure mechanism, because it is possible to successfully insert data after the server down, the corresponding data is not deleted, when the service has been restored after the lock has been acquired, so, you need to add a column in the table, to record the failure time, and need to have a scheduled task to clear the failed data;
4, does not have the blocking lock characteristic, obtains the lock to return the failure directly, therefore needs to optimize obtains the logic, the loop obtains several times.
5, in the process of implementation will encounter a variety of problems, in order to solve these problems, the way of implementation will be more and more complex; dependent on the database requires a certain amount of resource overhead, performance issues need to be considered.
V. Redis-based implementation approach
1. Choose Redis for distributed lock reasons:
(1) Redis has very high performance;
(2) Redis command is good for this support, it is more convenient to implement.
2, the use of command introduction:
(1) setnx:setnx key Val: If and only if key does not exist, set a string with a key of Val, return 1, and if key exists, do nothing and return 0.
(2) Expire:expire key timeout: Set a time-out for key, the unit is second, more than this time the lock will be automatically released, to avoid deadlocks.
(3) delete:delete key: Delete key
These three commands are used primarily when implementing distributed locks using Redis.
3, realize the idea:
(1) When acquiring the lock, use SETNX lock, and use the expire command to add a time-out for the lock, more than that time to automatically release the lock, the value of the lock is a randomly generated UUID, through this when the lock is released to judge.
(2) When the lock is acquired, a time-out is set, and if the time is exceeded, the acquisition lock is discarded.
(3) When the lock is released, it is determined by the UUID that it is not the lock, and if the lock is executed, the delete is performed for lock release.
4. The simple implementation Code of the distributed type Lock:
5. Testing the distributed locks just implemented
The example uses 50 threads to simulate seconds to kill a commodity, use the-operator to reduce the product, and from the order of the results can be seen whether the locking state.
Simulates a kill service in which a Jedis thread pool is configured, which is passed to the distributed lock for use at initialization time.
Impersonate a thread for a second kill service:
As a result, the results are ordered:
If you comment out the part that uses the lock:
As you can see from the results, some are asynchronous:
Java Multithreading-related