同步 InputStream 有什么好处?

What is the benefit of having synchronized an InputStream?

我最近使用了 Apache Commons-IO 的 class CountingInputStream。它只是通过更新计数器字段来跟踪读取了多少字节。

我注意到它用 synchronized keyword. The best source that I could find is IO-201 更新了计数器,但没有解释原因。

我在一些地方读到 Apache Commons 代码质量很好,但我现在想知道为什么他们在 InputStream 中有同步方法。我不相信线程安全在流上有用 属性,IO-201 的评论员也不相信。

鉴于我没有同时访问 InputStream,是否有任何正当理由同步其方法?或者是否有一个有效的用例来同时访问一个 InputStream 而不会产生数据垃圾?

Given that I'm not accessing an InputStream concurrently, is there any valid reason to have its methods synchronized?

不,您没有正当理由对仅从单个线程访问的对象使用同步方法。话虽如此,您正在使用 does 同步的第三方代码来保护可变状态(count 字段),因此除了实施之外您别无选择自己做。

Or is there a valid use case to access an InputStream concurrently which will not produce data garbage?

一个InputStream?可能不会。一个CountingInputStream?当然...在一个线程中,我反复调用 CountingInputStream.read() 来使用流,在另一个线程中,我反复调用 CountingInputStream.getCount() 来更新我的 UI 以显示我已阅读的行数。