Skip to content

Commit e08da01

Browse files
authored
Efficiency: Let thread do other tasks as long encoder/decoder is busy (#215)
Motivation: Busy loops are blocking valuable threads, so other tasks are blocked while the current task spins waiting. This reduces concurrency without a need, hence makes inefficient use of the existing hardware. Modification: Using `Thread.yield()` in all busy waiting loops. Result: Other tasks are allowed to run while encode / decoder is busy.
1 parent e14f7d4 commit e08da01

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

brotli4j/src/main/java/com/aayushatharva/brotli4j/decoder/BrotliInputStream.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ public int read() throws IOException {
8282
if (decoded != 0) {
8383
break;
8484
}
85+
Thread.yield();
8586
}
8687

8788
if (decoded == -1) {
@@ -105,7 +106,10 @@ public int read(byte[] b, int off, int len) throws IOException {
105106
}
106107
int result = 0;
107108
while (len > 0) {
108-
int limit = Math.min(len, decoder.buffer.remaining());
109+
int limit;
110+
while ((limit = Math.min(len, decoder.buffer.remaining())) == 0) {
111+
Thread.yield();
112+
}
109113
decoder.buffer.get(b, off, limit);
110114
off += limit;
111115
len -= limit;

brotli4j/src/main/java/com/aayushatharva/brotli4j/encoder/BrotliOutputStream.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public void write(int b) throws IOException {
8181
throw new IOException("write after close");
8282
}
8383
while (!encoder.encode(EncoderJNI.Operation.PROCESS)) {
84-
// Busy-wait loop.
84+
Thread.yield();
8585
}
8686
encoder.inputBuffer.put((byte) b);
8787
}
@@ -98,9 +98,13 @@ public void write(byte[] b, int off, int len) throws IOException {
9898
}
9999
while (len > 0) {
100100
if (!encoder.encode(EncoderJNI.Operation.PROCESS)) {
101+
Thread.yield();
101102
continue;
102103
}
103-
int limit = Math.min(len, encoder.inputBuffer.remaining());
104+
int limit;
105+
while ((limit = Math.min(len, encoder.inputBuffer.remaining())) == 0) {
106+
Thread.yield();
107+
}
104108
encoder.inputBuffer.put(b, off, limit);
105109
off += limit;
106110
len -= limit;

0 commit comments

Comments
 (0)