Che cos'è Thread-Safe BlockingQueue in Java? Quando dovresti usarlo? In allegato l'attuazione
Pubblicato: 2021-04-30
Finora ho scritto due articoli sul concetto di produttore consumatore su Crunchify. Il primo per spiegare Java Semaphore e Mutex e il secondo per spiegare la lettura/scrittura simultanea.
In questo tutorial Java esamineremo lo stesso concetto di produttore/consumatore per spiegare BlockingQueue in Java
.
Quali sono i vantaggi di Blocking Queue in Java?
Un java.util.Queue
supporta operazioni che aspettano che la coda diventi non vuota durante il recupero di un elemento e aspettano che lo spazio diventi disponibile nella coda durante la memorizzazione di un elemento.

Dobbiamo creare quattro classi Java:
- CrunchifyMessage.java per inserire e ricevere messaggi
- CrunchifyBlockingProducer.java per mettere il messaggio in coda
- CrunchifyBlockingConsumer.java per ottenere il messaggio dalla coda
- CrunchifyBlockingMain.java per avviare il test
Le implementazioni di BlockingQueue sono thread-safe
. Tutti i metodi di accodamento sono di natura atomica e utilizzano blocchi interni.
Iniziamo con l'implementazione Thread-Safe BlockingQueue in Java
Passo 1
Crea classe CrunchifyMessage.java
. Questo è un semplice oggetto 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 ; } } |
Passo 2
Crea il produttore CrunchifyBlockingProducer.java
che ha creato un semplice msg e lo metti in coda.
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 ) ; } } } |
Passaggio 3
Crea la classe CrunchifyBlockingConsumer.java
che consuma il messaggio dalla coda.
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 ( ) ; } } } |
Passaggio 4
Crea un semplice metodo CrunchifyBlockingMain.java
che esegue il test BlockingQueue. Esegui questo programma per verificare il comportamento di 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" ) ; } } |
Un BlockingQueue non accetta elementi null . Le implementazioni generano NullPointerException sui tentativi di aggiungere , inserire o offrire un valore null .
Un valore null viene utilizzato come valore sentinella per indicare il fallimento delle operazioni di polling .
Risultato:
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 . |
Quando dovremmo usare java.util.concurrent.BlockingQueue?
- Quando vuoi limitare una sorta di richiesta in arrivo, dovresti usare lo stesso
- Un produttore può anticipare di gran lunga i consumatori con una coda illimitata. Se il consumatore non sta raggiungendo il produttore, potrebbe causare un
OutOfMemoryError
. In situazioni come queste, potrebbe essere meglio segnalare a un aspirante produttore che la coda è piena e arrendersi rapidamente in caso di errore.- In altre parole: i produttori sono naturalmente strozzati.
- La coda di blocco viene normalmente utilizzata nell'applicazione simultanea
- Fornisce un'implementazione corretta e thread-safe
- Anche il consumo di memoria dovrebbe essere limitato