Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions src/main/java/org/apache/commons/io/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ static final class ScratchBytes implements AutoCloseable {
* [0] boolean in use.
* [1] byte[] buffer.
*/
private static final ThreadLocal<Object[]> LOCAL = ThreadLocal.withInitial(() -> new Object[] { false, new ScratchBytes(byteArray()) });
private static final ThreadLocal<Object[]> LOCAL = ThreadLocal.withInitial(() -> new Object[] { false, byteArray() });

private static final ScratchBytes INSTANCE = new ScratchBytes(null);

/**
* Gets the internal byte array buffer.
Expand All @@ -170,27 +172,30 @@ static ScratchBytes get() {
return new ScratchBytes(byteArray());
}
holder[0] = true;
return (ScratchBytes) holder[1];
return INSTANCE;
}

/**
* The buffer, or null if using the thread-local buffer.
*/
private final byte[] buffer;

private ScratchBytes(final byte[] buffer) {
this.buffer = buffer;
}

byte[] array() {
return buffer;
return buffer != null ? buffer : (byte[]) LOCAL.get()[1];
}

/**
* If the buffer is the internal array, clear and release it for reuse.
*/
@Override
public void close() {
final Object[] holder = LOCAL.get();
if (buffer == ((ScratchBytes) holder[1]).buffer) {
Arrays.fill(buffer, (byte) 0);
if (buffer == null) {
final Object[] holder = LOCAL.get();
Arrays.fill((byte[]) holder[1], (byte) 0);
holder[0] = false;
}
}
Expand Down Expand Up @@ -220,7 +225,9 @@ static final class ScratchChars implements AutoCloseable {
* [0] boolean in use.
* [1] char[] buffer.
*/
private static final ThreadLocal<Object[]> LOCAL = ThreadLocal.withInitial(() -> new Object[] { false, new ScratchChars(charArray()) });
private static final ThreadLocal<Object[]> LOCAL = ThreadLocal.withInitial(() -> new Object[] { false, charArray() });

private static final ScratchChars INSTANCE = new ScratchChars(null);

/**
* Gets the internal char array buffer.
Expand All @@ -234,27 +241,30 @@ static ScratchChars get() {
return new ScratchChars(charArray());
}
holder[0] = true;
return (ScratchChars) holder[1];
return INSTANCE;
}

/**
* The buffer, or null if using the thread-local buffer.
*/
private final char[] buffer;

private ScratchChars(final char[] buffer) {
this.buffer = buffer;
}

char[] array() {
return buffer;
return buffer != null ? buffer : (char[]) LOCAL.get()[1];
}

/**
* If the buffer is the internal array, clear and release it for reuse.
*/
@Override
public void close() {
final Object[] holder = LOCAL.get();
if (buffer == ((ScratchChars) holder[1]).buffer) {
Arrays.fill(buffer, (char) 0);
if (buffer == null) {
final Object[] holder = LOCAL.get();
Arrays.fill((char[]) holder[1], (char) 0);
holder[0] = false;
}
}
Expand Down