मैं सर्वलेट को धीमे कनेक्शन तो बुनियादी तौर पर मैं जो हर बाइट जोड़ देगा (छोटे बफ़र्स में) एक QueueOutputStream में सर्वलेट उत्पादन धारा लिपटे के लिए एक फिल्टर लागू करने के लिए किया था, एक कतार में, और उसके बाद उत्पादन उन छोटे बफर को दूसरी आउटपुट स्ट्रीम में, इसलिए एक तरह से यह इनपुट/आउटपुट स्ट्रीम के रूप में कार्य करता है, आईएमएचओ यह जेडीके पाइप से बेहतर है जो कि अच्छी तरह से स्केल नहीं करेगा, मूल रूप से मानक जेडीके कार्यान्वयन में बहुत अधिक संदर्भ स्विचिंग है (प्रति पढ़ें/लिखें), एक अवरुद्ध कतार एक निर्माता/उपभोक्ता परिदृश्य के लिए बिल्कुल सही है:
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.*;
public class QueueOutputStream extends OutputStream
{
private static final int DEFAULT_BUFFER_SIZE=1024;
private static final byte[] END_SIGNAL=new byte[]{};
private final BlockingQueue<byte[]> queue=new LinkedBlockingDeque<>();
private final byte[] buffer;
private boolean closed=false;
private int count=0;
public QueueOutputStream()
{
this(DEFAULT_BUFFER_SIZE);
}
public QueueOutputStream(final int bufferSize)
{
if(bufferSize<=0){
throw new IllegalArgumentException("Buffer size <= 0");
}
this.buffer=new byte[bufferSize];
}
private synchronized void flushBuffer()
{
if(count>0){
final byte[] copy=new byte[count];
System.arraycopy(buffer,0,copy,0,count);
queue.offer(copy);
count=0;
}
}
@Override
public synchronized void write(final int b) throws IOException
{
if(closed){
throw new IllegalStateException("Stream is closed");
}
if(count>=buffer.length){
flushBuffer();
}
buffer[count++]=(byte)b;
}
@Override
public synchronized void write(final byte[] b, final int off, final int len) throws IOException
{
super.write(b,off,len);
}
@Override
public synchronized void close() throws IOException
{
flushBuffer();
queue.offer(END_SIGNAL);
closed=true;
}
public Future<Void> asyncSendToOutputStream(final ExecutorService executor, final OutputStream outputStream)
{
return executor.submit(
new Callable<Void>()
{
@Override
public Void call() throws Exception
{
try{
byte[] buffer=queue.take();
while(buffer!=END_SIGNAL){
outputStream.write(buffer);
buffer=queue.take();
}
outputStream.flush();
} catch(Exception e){
close();
throw e;
} finally{
outputStream.close();
}
return null;
}
}
);
}
स्रोत
2013-10-19 12:23:21
आमेन! – Wivani
आप पाइप में PipedInputStream और एक PipedOutputStream कैसे जोड़ते हैं और उन्हें कनेक्ट करते हैं? – Sabobin