为什么没有更多的 Java 代码使用 PipedInputStream/PipedOutputStream? [英] Why doesn't more Java code use PipedInputStream / PipedOutputStream?
问题描述
我最近发现了这个成语,我想知道我是否遗漏了什么.我从未见过它被使用过.我在野外使用过的几乎所有 Java 代码都倾向于将数据放入字符串或缓冲区中,而不是像这个例子那样(例如使用 HttpClient 和 XML API):
I've discovered this idiom recently, and I am wondering if there is something I am missing. I've never seen it used. Nearly all Java code I've worked with in the wild favors slurping data into a string or buffer, rather than something like this example (using HttpClient and XML APIs for example):
final LSOutput output; // XML stuff initialized elsewhere
final LSSerializer serializer;
final Document doc;
// ...
PostMethod post; // HttpClient post request
final PipedOutputStream source = new PipedOutputStream();
PipedInputStream sink = new PipedInputStream(source);
// ...
executor.execute(new Runnable() {
public void run() {
output.setByteStream(source);
serializer.write(doc, output);
try {
source.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}});
post.setRequestEntity(new InputStreamRequestEntity(sink));
int status = httpClient.executeMethod(post);
该代码使用 Unix 管道风格技术来防止将 XML 数据的多个副本保存在内存中.它使用 HTTP Post 输出流和 DOM Load/Save API 将 XML 文档序列化为 HTTP 请求的内容.据我所知,它通过很少的额外代码(只有 Runnable
、PipedInputStream
和 PipedOutputStream
的几行代码)最大限度地减少了内存的使用).
That code uses a Unix-piping style technique to prevent multiple copies of the XML data being kept in memory. It uses the HTTP Post output stream and the DOM Load/Save API to serialize an XML Document as the content of the HTTP request. As far as I can tell it minimizes the use of memory with very little extra code (just the few lines for Runnable
, PipedInputStream
, and PipedOutputStream
).
那么,这个习语有什么问题?如果这个成语没毛病,我怎么没看到?
So, what's wrong with this idiom? If there's nothing wrong with this idiom, why haven't I seen it?
澄清一下,PipedInputStream
和 PipedOutputStream
替换了随处可见的样板缓冲区副本,它们还允许您同时处理传入数据写出处理后的数据.他们不使用操作系统管道.
to clarify, PipedInputStream
and PipedOutputStream
replace the boilerplate buffer-by-buffer copy that shows up everywhere, and they also allow you to process incoming data concurrently with writing out the processed data. They don't use OS pipes.
推荐答案
来自 Javadocs:
通常,数据由一个线程从 PipedInputStream 对象读取,数据由其他线程写入相应的 PipedOutputStream.不建议尝试从单个线程使用两个对象,因为这可能会使线程死锁.
Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.
这或许可以部分解释为什么它不常用.
This may partially explain why it is not more commonly used.
我认为另一个原因是许多开发人员不了解其目的/好处.
I'd assume another reason is that many developers do not understand its purpose / benefit.
这篇关于为什么没有更多的 Java 代码使用 PipedInputStream/PipedOutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!