Skip to content

Commit 064d083

Browse files
committed
BufferedInputStream: finish
1 parent 387bbd1 commit 064d083

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

note/BufferedInputStream/bufferedinputstream.md

+59
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,62 @@ ioctlsocket函数为系统调用,可用于设置或读取socket相关信息,
141141
142142
>Use to determine the amount of data pending in the network's input buffer that can be read from sockets. The argp parameter points to an unsigned long value in which ioctlsocket stores the result. FIONREAD returns the amount of data that can be read in a single call to the recv function, which may not be the same as the total amount of data queued on the socket. If s is message oriented (for example, type SOCK_DGRAM), FIONREAD still returns the amount of pending data in the network buffer, however, the amount that can actually be read in a single call to the recv function is limited to the data size written in the send or sendto function call.
143143
144+
# skip
145+
146+
```java
147+
public synchronized long skip(long n) throws IOException {
148+
getBufIfOpen(); // Check for closed stream
149+
if (n <= 0) {
150+
return 0;
151+
}
152+
long avail = count - pos;
153+
if (avail <= 0) {
154+
// If no mark position set then don't keep in buffer
155+
if (markpos <0)
156+
return getInIfOpen().skip(n);
157+
// Fill in buffer to save bytes for reset
158+
fill();
159+
avail = count - pos;
160+
if (avail <= 0)
161+
return 0;
162+
}
163+
long skipped = (avail < n) ? avail : n;
164+
pos += skipped;
165+
return skipped;
166+
}
167+
```
168+
169+
逻辑一目了然,不过注意下面这一行:
170+
171+
```java
172+
return getInIfOpen().skip(n);
173+
```
174+
175+
这里调用的是父类InputStream的同名方法,其实现非常简单粗暴: 直接读出需要跳过的数目的字节就好了。但是可以想象,对于文件输入流一定不是这样的实现,FileInputStream的源码证明了这一点:
176+
177+
```java
178+
public native long skip(long n) throws IOException;
179+
```
180+
181+
因为文件支持文件指针,直接移动文件指针便可以达到跳过字节的效果。
182+
183+
# close
184+
185+
```java
186+
public void close() throws IOException {
187+
byte[] buffer;
188+
while ( (buffer = buf) != null) {
189+
if (bufUpdater.compareAndSet(this, buffer, null)) {
190+
InputStream input = in;
191+
in = null;
192+
if (input != null)
193+
input.close();
194+
return;
195+
}
196+
// Else retry in case a new buf was CASed in fill()
197+
}
198+
}
199+
```
200+
201+
无锁情况下的CAS重试。
202+

0 commit comments

Comments
 (0)