@@ -288,19 +288,18 @@ private int timedRead(FileDescriptor fd, byte[] b, int off, int len, long nanos)
288
288
* @throws SocketException if the socket is closed or a socket I/O error occurs
289
289
* @throws SocketTimeoutException if the read timeout elapses
290
290
*/
291
- private int implRead (byte [] b , int off , int len ) throws IOException {
291
+ private int implRead (byte [] b , int off , int len , long remainingNanos ) throws IOException {
292
292
int n = 0 ;
293
293
FileDescriptor fd = beginRead ();
294
294
try {
295
295
if (connectionReset )
296
296
throw new SocketException ("Connection reset" );
297
297
if (isInputClosed )
298
298
return -1 ;
299
- int timeout = this .timeout ;
300
- configureNonBlockingIfNeeded (fd , timeout > 0 );
301
- if (timeout > 0 ) {
299
+ configureNonBlockingIfNeeded (fd , remainingNanos > 0 );
300
+ if (remainingNanos > 0 ) {
302
301
// read with timeout
303
- n = timedRead (fd , b , off , len , MILLISECONDS . toNanos ( timeout ) );
302
+ n = timedRead (fd , b , off , len , remainingNanos );
304
303
} else {
305
304
// read, no timeout
306
305
n = tryRead (fd , b , off , len );
@@ -335,14 +334,24 @@ private int read(byte[] b, int off, int len) throws IOException {
335
334
if (len == 0 ) {
336
335
return 0 ;
337
336
} else {
338
- readLock .lock ();
337
+ long remainingNanos = 0 ;
338
+ int timeout = this .timeout ;
339
+ if (timeout > 0 ) {
340
+ remainingNanos = tryLock (readLock , timeout , MILLISECONDS );
341
+ if (remainingNanos <= 0 ) {
342
+ assert !readLock .isHeldByCurrentThread ();
343
+ throw new SocketTimeoutException ("Read timed out" );
344
+ }
345
+ } else {
346
+ readLock .lock ();
347
+ }
339
348
try {
340
349
// emulate legacy behavior to return -1, even if socket is closed
341
350
if (readEOF )
342
351
return -1 ;
343
352
// read up to MAX_BUFFER_SIZE bytes
344
353
int size = Math .min (len , MAX_BUFFER_SIZE );
345
- int n = implRead (b , off , size );
354
+ int n = implRead (b , off , size , remainingNanos );
346
355
if (n == -1 )
347
356
readEOF = true ;
348
357
return n ;
0 commit comments