same:
1. LinkedBlockingQueue and ArrayBlockingQueue both implement the BlockingQueue interface;
2. LinkedBlockingQueue and ArrayBlockingQueue are both blockable queues
ReentrantLock and Condition are used internally to ensure the synchronization of production and consumption;
When the queue is empty, the consumer thread is blocked; when the queue is full, the producer thread is blocked;
Use the Condition method to synchronize and communicate: await() and signal()
different:
1. As can be seen from the above picture, their locking mechanism is different.
The locks in LinkedBlockingQueue are separated, the producer's lock PutLock, and the consumer's lock takeLock
ArrayBlockingQueue producers and consumers use the same lock;
2. Their underlying implementation mechanism is also different
LinkedBlockingQueue maintains a linked list structure internally
During production and consumption, Node objects need to be created for insertion or removal. In systems with large batches of data, the pressure on GC will be greater.
ArrayBlockingQueue maintains an array internally
During production and consumption, enumeration objects are directly inserted or removed, and no additional object instances are generated or destroyed.
3. Differences in construction
LinkedBlockingQueue has a default capacity size: Integer.MAX_VALUE, of course, you can also pass in the specified capacity size.
When initializing ArrayBlockingQueue, a value of capacity must be passed in.
You can know by looking at the construction method provided by it
4. Execute the clear() method
When LinkedBlockingQueue executes the clear method, two locks will be added.
5. Statistics the number of elements
A AtomicInteger object is used in LinkedBlockingQueue to count the number of elements
ArrayBlockingQueue uses the int type to count elements