Co to jest bezpieczna dla wątków kolejka blokowania w Javie? Kiedy należy go używać? Załączona implementacja
Opublikowany: 2021-04-30
Do tej pory napisałem dwa artykuły na temat koncepcji Producer Consumer na Crunchify. Pierwszy wyjaśniający Java Semaphore i Mutex, a drugi wyjaśniający współbieżny odczyt/zapis.
W tym samouczku Java omówimy tę samą koncepcję producenta/konsumentu, aby wyjaśnić BlockingQueue in Java
.
Jakie są zalety kolejki blokowania w Javie?
java.util.Queue
obsługuje operacje, które czekają, aż kolejka stanie się niepusta podczas pobierania elementu i czekają, aż miejsce w kolejce stanie się dostępne podczas przechowywania elementu.

Musimy stworzyć cztery klasy Java:
- CrunchifyMessage.java umieścić i otrzymać wiadomość
- CrunchifyBlockingProducer.java, aby umieścić wiadomość w kolejce
- CrunchifyBlockingConsumer.java, aby pobrać wiadomość z kolejki
- CrunchifyBlockingMain.java, aby rozpocząć test
Implementacje BlockingQueue są thread-safe
. Wszystkie metody kolejkowania mają charakter atomowy i wykorzystują wewnętrzne blokady.
Zacznijmy od implementacji Thread-Safe BlockingQueue w Javie
Krok 1
Utwórz klasę CrunchifyMessage.java
. To jest prosty obiekt Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com . crunchify . example ; /** * @author Crunchify.com * simple Message class to put and get message into queue */ public class CrunchifyMessage { private String crunchifyMsg ; public CrunchifyMessage ( String string ) { this . crunchifyMsg = string ; } public String getMsg ( ) { return crunchifyMsg ; } } |
Krok 2
Utwórz producenta CrunchifyBlockingProducer.java
, który utworzył prostą wiadomość i umieścił ją w kolejce.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com . crunchify . example ; import java . util . concurrent . BlockingQueue ; /** * @author Crunchify.com * */ public class CrunchifyBlockingProducer implements Runnable { private BlockingQueue <CrunchifyMessage> crunchQueue ; public CrunchifyBlockingProducer ( BlockingQueue <CrunchifyMessage> queue ) { this . crunchQueue = queue ; } @Override public void run ( ) { // producing CrunchifyMessage messages for ( int i = 1 ; i < = 5 ; i ++ ) { CrunchifyMessage msg = new CrunchifyMessage ( "i'm msg " + i ) ; try { Thread . sleep ( 10 ) ; crunchQueue . put ( msg ) ; System . out . println ( "CrunchifyBlockingProducer: Message - " + msg . getMsg ( ) + " produced." ) ; } catch ( Exception e ) { System . out . println ( "Exception:" + e ) ; } } // adding exit message CrunchifyMessage msg = new CrunchifyMessage ( "All done from Producer side. Produced 50 CrunchifyMessages" ) ; try { crunchQueue . put ( msg ) ; System . out . println ( "CrunchifyBlockingProducer: Exit Message - " + msg . getMsg ( ) ) ; } catch ( Exception e ) { System . out . println ( "Exception:" + e ) ; } } } |
Krok 3
Utwórz klasę CrunchifyBlockingConsumer.java
, która zużywa wiadomość z kolejki.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com . crunchify . example ; import java . util . concurrent . BlockingQueue ; /** * @author Crunchify.com * */ public class CrunchifyBlockingConsumer implements Runnable { private BlockingQueue <CrunchifyMessage> queue ; public CrunchifyBlockingConsumer ( BlockingQueue <CrunchifyMessage> queue ) { this . queue = queue ; } @Override public void run ( ) { try { CrunchifyMessage msg ; // consuming messages until exit message is received while ( ( msg = queue . take ( ) ) . getMsg ( ) ! = "exit" ) { Thread . sleep ( 10 ) ; System . out . println ( "CrunchifyBlockingConsumer: Message - " + msg . getMsg ( ) + " consumed." ) ; } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } |
Krok 4
Utwórz prostą metodę CrunchifyBlockingMain.java
, która uruchamia test BlockingQueue. Uruchom ten program, aby sprawdzić zachowanie BlockingQueue.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com . crunchify . example ; import java . util . concurrent . ArrayBlockingQueue ; import java . util . concurrent . BlockingQueue ; /** * @author Crunchify.com * */ public class CrunchifyBlockingMain { public static void main ( String [ ] args ) { // Creating BlockingQueue of size 10 // BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element, and // wait for space to become available in the queue when storing an element. BlockingQueue <CrunchifyMessage> crunchQueue = new ArrayBlockingQueue < > ( 10 ) ; CrunchifyBlockingProducer crunchProducer = new CrunchifyBlockingProducer ( crunchQueue ) ; CrunchifyBlockingConsumer crunchConsumer = new CrunchifyBlockingConsumer ( crunchQueue ) ; // starting producer to produce messages in queue new Thread ( crunchProducer ) . start ( ) ; // starting consumer to consume messages from queue new Thread ( crunchConsumer ) . start ( ) ; System . out . println ( "Let's get started. Producer / Consumer Test Started.\n" ) ; } } |
BlockingQueue nie akceptuje elementów o wartości null . Implementacje generują NullPointerException przy próbach dodania , umieszczenia lub zaoferowania wartości null .
Wartość null jest używana jako wartość wskaźnikowa wskazująca niepowodzenie operacji odpytywania .
Wynik:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Let 's get started. Producer / Consumer Test Started. CrunchifyBlockingProducer: Message - i' m msg 1 produced . CrunchifyBlockingProducer : Message - i 'm msg 2 produced. CrunchifyBlockingConsumer: Message - i' m msg 1 consumed . CrunchifyBlockingConsumer : Message - i 'm msg 2 consumed. CrunchifyBlockingProducer: Message - i' m msg 3 produced . CrunchifyBlockingConsumer : Message - i 'm msg 3 consumed. CrunchifyBlockingProducer: Message - i' m msg 4 produced . CrunchifyBlockingConsumer : Message - i 'm msg 4 consumed. CrunchifyBlockingProducer: Message - i' m msg 5 produced . CrunchifyBlockingProducer : Exit Message - All done from Producer side . Produced 50 CrunchifyMessages CrunchifyBlockingConsumer : Message - i ' m msg 5 consumed . CrunchifyBlockingConsumer : Message - All done from Producer side . Produced 50 CrunchifyMessages consumed . |
Kiedy powinniśmy używać java.util.concurrent.BlockingQueue?
- Jeśli chcesz ograniczyć przychodzące żądanie, powinieneś użyć tego samego
- Dzięki niekończącej się kolejce producenci mogą wyprzedzić konsumentów. Jeśli konsument nie dogania producenta, może to spowodować
OutOfMemoryError
. W takich sytuacjach może lepiej zasygnalizować niedoszłemu producentowi, że kolejka jest pełna, i szybko zrezygnować z awarii.- Innymi słowy: producenci są naturalnie dławieni.
- Kolejka blokowania jest zwykle używana w aplikacji współbieżnej
- Zapewnia poprawną, bezpieczną wątkowo implementację
- Zużycie pamięci również powinno być ograniczone