|
22 | 22 | import java.io.PipedOutputStream;
|
23 | 23 | import java.io.Reader;
|
24 | 24 | import java.nio.charset.StandardCharsets;
|
| 25 | +import java.time.Instant; |
| 26 | +import java.time.temporal.ChronoUnit; |
25 | 27 | import java.util.HashMap;
|
26 | 28 | import java.util.Map;
|
27 | 29 | import okhttp3.WebSocket;
|
@@ -212,9 +214,9 @@ private class WebSocketOutputStream extends OutputStream {
|
212 | 214 |
|
213 | 215 | private static final long MAX_QUEUE_SIZE = 16L * 1024 * 1024;
|
214 | 216 |
|
215 |
| - private static final int MAX_QUEUE_SIZE_MAX_ATTEMPTS = 15; |
| 217 | + private static final int MAX_WAIT_MILLIS = 10000; |
216 | 218 |
|
217 |
| - private static final int MAX_QUEUE_SIZE_WAIT_MILLISECONDS = 1000; |
| 219 | + private static final int WAIT_MILLIS = 10; |
218 | 220 |
|
219 | 221 | private final byte stream;
|
220 | 222 |
|
@@ -276,19 +278,22 @@ public void write(byte[] b, int offset, int length) throws IOException {
|
276 | 278 | System.arraycopy(b, offset + bytesWritten, buffer, 1, bufferSize);
|
277 | 279 | ByteString byteString = ByteString.of(buffer);
|
278 | 280 |
|
279 |
| - int attempts = 0; |
280 |
| - while (WebSocketStreamHandler.this.socket.queueSize() + byteString.size() > MAX_QUEUE_SIZE |
281 |
| - && attempts < MAX_QUEUE_SIZE_MAX_ATTEMPTS) { |
282 |
| - try { |
283 |
| - Thread.sleep(MAX_QUEUE_SIZE_WAIT_MILLISECONDS); |
284 |
| - attempts++; |
285 |
| - } catch (InterruptedException e) { |
286 |
| - throw new IOException("Error waiting web socket queue", e); |
| 281 | + final Instant start = Instant.now(); |
| 282 | + synchronized (WebSocketOutputStream.this) { |
| 283 | + while (WebSocketStreamHandler.this.socket.queueSize() + byteString.size() > MAX_QUEUE_SIZE |
| 284 | + && Instant.now().isBefore(start.plus(MAX_WAIT_MILLIS, ChronoUnit.MILLIS))) { |
| 285 | + try { |
| 286 | + wait(WAIT_MILLIS); |
| 287 | + } catch (InterruptedException e) { |
| 288 | + throw new IOException("Error waiting web socket queue", e); |
| 289 | + } |
| 290 | + } |
| 291 | + |
| 292 | + if (!WebSocketStreamHandler.this.socket.send(byteString)) { |
| 293 | + throw new IOException("WebSocket has closed."); |
287 | 294 | }
|
288 |
| - } |
289 | 295 |
|
290 |
| - if (!WebSocketStreamHandler.this.socket.send(byteString)) { |
291 |
| - throw new IOException("WebSocket has closed."); |
| 296 | + notifyAll(); |
292 | 297 | }
|
293 | 298 |
|
294 | 299 | bytesWritten += bufferSize;
|
|
0 commit comments