KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > util > OutgoingBufferPool


1 package org.jgroups.util;
2
3 import java.util.concurrent.ArrayBlockingQueue JavaDoc;
4 import java.util.concurrent.BlockingQueue JavaDoc;
5
6 /**
7  * Maintains a pool of ExposedDataOutputStreams. The main reason is that a ByteArrayOutputStream starts with 1024
8  * bytes, and almost always increases to 65K (max size of a UDP datagram). We save a few copies when the BAOS increases
9  * its size by pooling those.
10  * @author Bela Ban
11  * @version $Id: OutgoingBufferPool.java,v 1.1 2007/01/07 01:24:52 belaban Exp $
12  */

13 public class OutgoingBufferPool {
14     private BlockingQueue JavaDoc<ExposedDataOutputStream> buffers;
15
16
17     public OutgoingBufferPool(int capacity) {
18         buffers=new ArrayBlockingQueue JavaDoc<ExposedDataOutputStream>(capacity);
19         for(int i=0; i < capacity; i++) {
20             ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(1024);
21             ExposedDataOutputStream dos=new ExposedDataOutputStream(out_stream);
22             try {
23                 buffers.put(dos);
24             }
25             catch(InterruptedException JavaDoc e) {
26                 Thread.currentThread().interrupt();
27                 return;
28             }
29         }
30     }
31
32
33     public ExposedDataOutputStream take() throws InterruptedException JavaDoc {
34         return buffers.take();
35     }
36
37     public void put(ExposedDataOutputStream buf) throws InterruptedException JavaDoc {
38         ((ExposedByteArrayOutputStream)buf.getOutputStream()).reset();
39         buf.reset();
40         buffers.put(buf);
41     }
42
43
44     public String JavaDoc dumpStats() {
45         ExposedByteArrayOutputStream stream;
46         StringBuilder JavaDoc sb=new StringBuilder JavaDoc();
47         sb.append(buffers.size()).append(" elements, capacities:\n");
48         for(ExposedDataOutputStream buf: buffers) {
49             stream=(ExposedByteArrayOutputStream)buf.getOutputStream();
50             sb.append("size=").append(stream.size()).append(", capacity=").append(stream.getCapacity()).append(")\n");
51         }
52         return sb.toString();
53     }
54
55
56 }
57
Popular Tags