2009年4月14日 星期二

LinkedBlockingQueue< E >

Producer跟comsumer這種pattern在程式設計很實用也常見到,在此pattern通常會搭配一個FIFO queue,意即,producer負責把東西塞進queue裏,而consumer再從中取出。

之前用到此pattern的開發經驗是,使用database時,會以一獨立之thread扮演consumer角色負責將queue中的sql command取出並依序執行之。藉此,在程式執行期間,程式與database間只會有一connection至於避免與database間建立太多conncetion的優點是...
是...
是...
我真的忘記了...囧。

總之,建立太多connection會有一些問題產生,因此才有人開發了connection pool這一套件,用以限制與database的connection數量..(這樣應該凹的不會太過分吧..XD)。

之前開發的時候為了應用此pattern,當初我們還藉由ArrayList、vector、hashtable之類的class自己implement一class。但,今天看了google的souce code後發現,若非有特殊需求,其實,只要用java.util.concurrent裡的LinkedBlockingQueueArrayBlockingQueue即可。

以下為j2se java doc的說明內容:

public class LinkedBlockingQueue
extends AbstractQueue
implements BlockingQueue, Serializable

An optionally-bounded blocking queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.

The optional capacity bound constructor argument serves as a way to prevent excessive queue expansion. The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

This class is a member of the Java Collections Framework.



google用到的function:

boolean offer(E o)
Inserts the specified element at the tail of this queue if possible, returning immediately if this queue is full.
Etake()
Retrieves and removes the head of this queue, waiting if no elements are present on this queue.

沒有留言:

張貼留言