In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "what are the methods to achieve concurrency in Java". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "what are the ways to achieve concurrency in Java" can help you solve the problem.
Several methods of realizing concurrency in Java
The Java program runs in a single thread by default.
Synchronized
Java has used the synchronized keyword to ensure that only one thread is executing the code block at a time.
Public synchronized void code () {/ / TODO} Volatile
The Volatile keyword ensures that when any thread reads a Volatile-decorated variable, it reads the latest data for that variable.
Threads and Runnablepublic class MyRunnable implements Runnable {@ Override public void run () {/ / TODO}} import java.util.ArrayList;import java.util.List;public class Main {public static void main (String [] args) {Runnable task = new MyRunnable (); Thread worker = new Thread (task); worker.setName ('Myrunnable'); worker.start ();}
Creating a thread will have a lot of overhead, low performance and difficult to manage
Thread poolsimport java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main {private static final int NUMOFTHREDS = 5; public static void main (String [] args) {ExecutorService executor = Executors.newFixedThreadPool (NUMOFTHREDS); for (int I = 0; I
< 50; i++) { Runnable worker = new MyRunnable(i); executor.execute(worker); } // executor不接受新的threads executor.shutdown(); // 等待所有threads结束 executor.awaitTermination(); System.out.println("Finished all threads"); }}Futures 和 Callables 因为Runnable对象无法向调用者返回结果,我们可以用Callable类来返回结果。 package de.vogella.concurrency.callables;import java.util.concurrent.Callable;public class MyCallable implements Callable { @Override public Long call() throws Exception { // TODO int sum = 1; return sum; }}import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class CallableFutures { private static final int NUMOFTHREDS = 5; public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(NUMOFTHREDS); List list = new ArrayList(); for (int i = 0; i < 10; i++) { Callable worker = new MyCallable(); Future submit = executor.submit(worker); list.add(submit); } long sum = 0; for (Future future : list) { try { sum += future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } System.out.println(sum); executor.shutdown(); }}CompletableFuture CompletableFuture 在Future的基础上增加了异步调用的功能。callback()函数Thread执行结束的时候会自动调用。 CompletableFuture既支持阻塞,也支持非阻塞的callback() import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutionException;public class CompletableFutureSimpleSnippet { public static void main(String[] args) { CompletableFuture data = createCompletableFuture() .thenApply((Integer count) ->{int transformedValue = count * 10; return transformedValue;}); try {int count = futureCount.get () } catch (InterruptedException | ExecutionException ex) {}} private static CompletableFuture createCompletableFuture () {CompletableFuture futureCount = CompletableFuture.supplyAsync (()-> {return 1;}); return futureCount;}}
Add: how does Java handle high concurrency situations
In order to better understand concurrency and synchronization, we need to understand two important concepts: synchronization and asynchronism.
The so-called synchronization can be understood as waiting for the return value or message of the system after the execution of a function or method, when the program is blocked and other commands are executed only after receiving the returned value or message. Synchronization is one thing, one thing to do.
Async, after executing the function or method, you do not have to wait for the return value or message obstructively, but only need to delegate an asynchronous process to the system, then when the system receives the return value or message, the system will automatically trigger the asynchronous process of the delegate. to complete a complete process. Asynchronism is to do one thing without affecting other things.
Synchronization keyword synchronized, if the synchronization monitoring object is a class, then if an object accesses the synchronization method in the class, then other objects will block if they want to continue to access the synchronization method in the class. Only after the previous object executes the synchronization method can the current object continue to execute the method. This is synchronization. On the contrary, if there is no synchronous keyword modification before the method, then different objects can access the same method at the same time, which is asynchronous.
Dirty data: when a transaction is accessing the data and making changes to the data that have not yet been committed to the database, another transaction accesses the data and then uses the data. Because this data is data that has not yet been committed, then the data read by another transaction is dirty data (Dirty Data), and the operation based on dirty data may be incorrect.
1. What is concurrency problem
Concurrency problems arise when multiple processes or threads access the same resource at the same time.
For example, An and B operators read an account with a balance of 1000 yuan at the same time, An operator increases the account by 100 yuan, and B operator subtracts 50 yuan from the account at the same time. In the end, the actual account balance was 1000-50,950 yuan, but it should have been 100000100-501050. This is a typical concurrency problem. How to solve?
The problem of concurrency and synchronization is mainly dealt with through the locking mechanism.
2. How to deal with concurrency and synchronization
One is the synchronization lock in java, typically the synchronization keyword synchronized.
Another typical one is pessimistic lock and optimistic lock.
There are two ways to implement atomic operations (that is, synchronous operations) in java:
1) use the synchronization keyword synchronized
2) use lock lock mechanism, which also includes the corresponding read-write lock
Pessimistic lock, as its name suggests, refers to a conservative attitude towards the modification of data by the outside world (including other current transactions of the system, as well as transactions from external systems), so that the data is locked throughout the data processing process.
Optimistic locks are mostly implemented based on the data version Version) recording mechanism. What is the data version? That is, to add a version identity to the data, which is generally achieved by adding a "version" field to the database table in the version solution based on the database table. When reading out the data, read out the version number together, and then add one to the version number when it is updated. At this point, the version data of the submitted data is compared with the current version information recorded in the corresponding database table, and if the submitted data version number is greater than the current version number of the database table, it will be updated, otherwise it is regarded as out-of-date data.
The optimistic locking mechanism is implemented in our system, and the user balance update operation from the external system is not controlled by our system, so it may cause dirty data to be updated to the database. In the system design stage, we should fully consider the possibility of these situations and make corresponding adjustments (for example, the optimistic locking strategy is implemented in the database stored procedure, and only the data update path based on this stored procedure is open to the public. Instead of exposing database tables directly).
Beware here, the interviewer will ask questions about deadlocks! The issue of deadlock is explained in one of the other blogs]
3. Case study of common concurrent synchronization cases 1. Case of booking system
There is only one ticket for a flight, suppose 1w individuals open your website to book tickets and ask you how to solve the concurrency problem (which can be extended to the concurrent reading and writing problems to be considered by any highly concurrent website).
Suppose we use synchronization mechanism or database physical lock mechanism, how to ensure that individuals can see tickets at the same time, obviously at the expense of performance, which is not desirable in highly concurrent websites.
This problem can be solved by using optimistic locks. Optimistic locking means that without locking the table, business control is used to solve the concurrency problem, which ensures the concurrency readability of data and the exclusiveness of data preservation, ensures performance and solves the problem of dirty data caused by concurrency.
How to achieve optimistic locking:
Premise: add a redundant field, version version number, long type to the existing table
Principle:
1) only the current version number > = database table version number can be submitted.
2) after successful submission, the version number version + +
Case 2, stock trading system, banking system, how do you consider a large amount of data?
First of all, in the performance table of the stock trading system, a market record is generated every few seconds, and there are 6 records of the number of stocks in a day (assuming a market in 3 seconds). What is the number of records in this table in January? The query performance is very poor when the number of records in a table exceeds 100w. How to ensure the system performance?
For example, China Mobile has hundreds of millions of users, how to design the watch? Use it all to exist in one table?
Therefore, a large number of systems must consider table splitting-(the table name is different, but the structure is exactly the same), several common ways: (as the case may be)
1) by business, such as the list of mobile phone numbers, we can consider a table starting with 130, another table starting with 131, and so on.
2) use the table splitting mechanism to make sub-tables.
3) if it is a trading system, we can consider splitting it according to the timeline, with one table for the day's data and other tables for the historical data. The reports and queries of historical data here will not affect daily trading.
In addition, we have to consider caching
The cache here is independent of the application and is still read from memory. If we can reduce the frequent access to the database, it will certainly be of great benefit to the system. For example, in the product search of an e-commerce system, if the items of a keyword are often searched, you can consider storing the list of items in the cache (in memory), so that you do not have to visit the database every time, and the performance is greatly improved.
4. The common means to improve the efficiency of access under high concurrency is to first understand where the bottleneck of high concurrency is.
1. The network bandwidth of the server may not be enough.
two。 There may not be enough web thread connections.
3. Maybe the database connection query can't go up.
According to different situations, the solution is also different.
1. As in the first case, you can increase the network bandwidth, and DNS domain name resolution distributes multiple servers.
2. Load balancing, pre-proxy server nginx, apache, etc.
3. Database query optimization, read-write separation, table division, etc.
Finally, copy some content that often needs to be dealt with under high concurrency.
1. Try to use caching, including user caching, information caching and so on. Spending more memory to do caching can greatly reduce the interaction with the database and improve performance.
2. Use jprofiler and other tools to find out the performance bottleneck and reduce the extra overhead.
3. Optimize database query statements and reduce the direct generation of statements directly using tools such as hibernate (only time-consuming queries are optimized).
4. Optimize the database structure and do more indexes to improve the query efficiency.
5, the function of statistics as far as possible cache, or according to a daily statistics or regular statistics related reports, to avoid the function of statistics when needed.
6, where static pages can be used as much as possible, reduce the parsing of containers (try to generate static html to display dynamic content).
7. After solving the above problems, use the server cluster to solve the bottleneck problem of a single machine.
This is the end of the content about "what are the ways to achieve concurrency in Java". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.