In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article shares with you the content of an example analysis of blocking queues in Java. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. What is a blocking queue?
Blocking queue is a special kind of queue, which, like ordinary queues in data structures, also follows the principle of first-in, first-out. At the same time, blocking queue is a data structure that ensures thread safety and has the following two characteristics: when the queue is full, continue to insert elements into the queue will cause the queue to block until other threads remove elements from the queue. When the queue is empty, continuing to leave the queue also blocks the queue until another thread inserts an element into the queue
Add: thread blocking means that the code will not be executed at this time, that is, the operating system will not schedule this thread to CPU for execution at this time.
two。 The code for blocking the queue uses import java.util.concurrent.LinkedBlockingDeque;import java.util.concurrent.BlockingDeque;public class Test {public static void main (String [] args) throws InterruptedException {/ / cannot directly newBlockingDeque, because it is an interface to be transformed upwards / / LinkedBlockingDeque is implemented internally based on a linked list BlockingDeque queue=new LinkedBlockingDeque (10) / / you can specify a specific number here, where 10 represents the maximum capacity of the queue queue.put ("hello"); String elem=queue.take (); System.out.println (elem); elem=queue.take (); System.out.println (elem);}}
Note: put method has blocking function, but offer does not, so put method is generally used (the reason why offer method can be used is that BlockingDeque inherits Queue)
As shown above, when the hello is printed, the queue is empty and the code executes to elem=queue.take (); it will not continue to execute, when the thread enters a blocking waiting state and nothing will be printed until another thread puts a new element into the queue
3. Producer-consumer model
Producer-consumer model is a common programming method in server development and back-end development, which is generally used for decoupling and peak-cutting and valley-filling.
High coupling: the relationship between the two code modules is relatively high.
High cohesion: the close combination of elements within a code module
Therefore, we generally pursue high cohesion and low coupling, which will speed up the execution efficiency, while the producer-consumer model can be decoupled.
(1) Application 1: decoupling
Let's take the real-life situation as an example, there are two servers: a server and B server. When A server transmits data to B, if it transmits data directly, then either A pushes data to B or B pulls data from A. both need An and B to interact directly, so An and B have a dependency relationship (An and B have a high degree of coupling). In the future, if the server needs to be expanded, such as adding a C server to let A send data to C, then the change will be more complex and will reduce efficiency. At this time, we can add a queue, which is classified as a blocking queue. If A writes the data to the queue and B takes it from it, then the queue is equivalent to a transit station (or trading place), An is equivalent to the producer (providing data), and B is equivalent to the consumer (receiving the data), which constitutes the producer-consumer model, which makes the code less coupled, easier to maintain, and more efficient.
In the computer, the producer acts as one set of threads, the consumer acts as another set of threads, and the trading floor can use blocking queues
(2) Application 2: cutting peak and filling valley
In real life
The dam is a very important part of the river. If there is no dam, imagine the result: when there is a lot of water upstream after the flood season, there will be a large amount of water downstream and the crops will be flooded. During the drought period, the downstream water is rarely likely to cause drought. If there is a dam, during the flood season, the dam stores excess water in the dam and closes the sluice to store water, so that the water upstream flows down at a certain rate, so as to avoid flooding downstream by a sudden wave of heavy rain. During the drought period, the dam releases the previously stored water, or lets the water flow down at a certain rate to avoid being too short of water, so as to avoid both flood and drought in the flood season.
Peak: equivalent to flood season
Valley: equivalent to a dry period
In the computer
This situation is also typical in computers, especially in server development, gateways usually forward requests from the Internet to business servers, such as some commodity servers and user servers. merchant server (store merchant information), live broadcast server. However, because the number of requests from the Internet is small and uncontrollable, which is equivalent to the water upstream, if there is a sudden wave of requests, even if the gateway can withstand, many subsequent servers will crash when they receive a lot of requests (processing a request involves a series of database operations, because the database-related operation itself is relatively inefficient, so too many requests can't be processed, so it will crash.)
Therefore, in practice, a queue is often used to buffer between the gateway and the business server, which is the blocking queue (trading place), which is used to implement the producer (gateway) consumer (business server) model. The request is cached in the queue, and the subsequent consumer (business server) reads the request at its own fixed rate. In this way, when there are many requests, although the queue server may be under a little pressure, it can ensure the security of the business server.
(3) the related code import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;public class TestDemo {public static void main (String [] args) {/ / uses a BlockingQueue as the trading venue BlockingQueue queue = new LinkedBlockingQueue () / / this thread as a consumer Thread customer = new Thread () {@ Override public void run () {while (true) {/ / fetch the first element try {Integer value = queue.take () System.out.println ("consumption element:" + value);} catch (InterruptedException e) {e.printStackTrace ();}; customer.start () / / this thread as a producer Thread producer = new Thread () {@ Override public void run () {for (int I = 1; I = items.length) {tail = 0;} size++; locker.notify () }} / / take is used to exit the queue public int take () throws InterruptedException {int ret = 0; synchronized (locker) {while (size = = 0) {/ / for blocking queues, if the queue is empty, if you try to fetch elements again, you will block locker.wait () } ret = items [head]; head++; if (head > = items.length) {head = 0;} size--; / / the notify here is used to wake up wait locker.notify () in put;} return ret }} public static void main (String [] args) throws InterruptedException {BlockingQueue queue = new BlockingQueue (); / / Consumer thread Thread consumer = new Thread () {@ Override public void run () {while (true) {try {int elem = queue.take () System.out.println ("consumption element:" + elem);} catch (InterruptedException e) {e.printStackTrace ();}; consumer.start () / / producer thread Thread producer = new Thread () {@ Override public void run () {for (int I = 1; I < 10000; iTunes +) {System.out.println ("production element:" + I); try {queue.put (I) Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();}; producer.start (); consumer.join (); producer.join ();}}
The running result is as above.
Note:
Correct use of 1.wait and notify
Both 2.put and take will cause blocking, but the blocking conditions are opposite and wait will not trigger at the same time (put Wake up take blocking, take Wake put blocking)
Thank you for reading! This is the end of this article on "sample analysis of blocking queues in Java". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.