Skip to content

Commit

Permalink
Using Java9+ NIO API for improved performance: Modern JREs offload to…
Browse files Browse the repository at this point in the history
… OS, and do other tricks.
  • Loading branch information
mkarg authored and jansupol committed May 9, 2024
1 parent 59b7d65 commit 21668db
Show file tree
Hide file tree
Showing 29 changed files with 104 additions and 156 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2024 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
Expand Down Expand Up @@ -743,7 +743,8 @@ private static InputStream getInputStream(final CloseableHttpResponse response,
if (i.markSupported()) {
inputStream = i;
} else {
inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
inputStream = ReaderWriter.AUTOSIZE_BUFFER ? new BufferedInputStream(i)
: new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2024 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
Expand Down Expand Up @@ -754,7 +754,8 @@ private static InputStream getInputStream(final CloseableHttpResponse response,
if (i.markSupported()) {
inputStream = i;
} else {
inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
inputStream = ReaderWriter.AUTOSIZE_BUFFER ? new BufferedInputStream(i)
: new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public abstract class AbstractMessageReaderWriterProvider<T> implements MessageB
*
* @deprecated use {@code StandardCharsets.UTF_8} instead.
*/
@Deprecated
@Deprecated(forRemoval = true)
public static final Charset UTF8 = StandardCharsets.UTF_8;

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2019 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
Expand Down Expand Up @@ -62,7 +62,7 @@ public final class CommittingOutputStream extends OutputStream {
* Null stream provider.
*/
private static final OutboundMessageContext.StreamProvider NULL_STREAM_PROVIDER =
contentLength -> new NullOutputStream();
contentLength -> OutputStream.nullOutputStream();
/**
* Default size of the buffer which will be used if no user defined size is specified.
*/
Expand Down Expand Up @@ -170,7 +170,7 @@ private void commitStream(int currentSize) throws IOException {
Preconditions.checkState(streamProvider != null, STREAM_PROVIDER_NULL);
adaptedOutput = streamProvider.getOutputStream(currentSize);
if (adaptedOutput == null) {
adaptedOutput = new NullOutputStream();
adaptedOutput = OutputStream.nullOutputStream();
}

directWrite = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,8 @@ public void writeTo(
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException {
try {
try (t) {
ReaderWriter.writeTo(t, entityStream);
} finally {
t.close();
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
* A utility class for reading and writing using byte and character streams.
* <p>
* If a byte or character array is utilized then the size of the array
* is by default the value of {@value org.glassfish.jersey.message.MessageProperties#IO_DEFAULT_BUFFER_SIZE}.
* is by default decided by the JRE.
* This value can be set using the system property
* {@value org.glassfish.jersey.message.MessageProperties#IO_BUFFER_SIZE}.
*
Expand All @@ -57,14 +57,19 @@ public final class ReaderWriter {
*
* @deprecated use {@code StandardCharsets.UTF_8} instead
*/
@Deprecated
@Deprecated(forRemoval = true)
public static final Charset UTF8 = StandardCharsets.UTF_8;
/**
* The buffer size for arrays of byte and character.
*/
public static final int BUFFER_SIZE = getBufferSize();

private static int getBufferSize() {
/**
* Whether {@linkplain BUFFER_SIZE} is to be ignored in favor of JRE's own decision.
*/
public static final boolean AUTOSIZE_BUFFER = getAutosizeBuffer();

private static int getIOBufferSize() {
// TODO should we unify this buffer size and CommittingOutputStream buffer size (controlled by CommonProperties.OUTBOUND_CONTENT_LENGTH_BUFFER)?
final String value = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(MessageProperties.IO_BUFFER_SIZE));
if (value != null) {
Expand All @@ -78,11 +83,20 @@ private static int getBufferSize() {
LOGGER.log(Level.CONFIG,
"Value of " + MessageProperties.IO_BUFFER_SIZE
+ " property is not a valid positive integer [" + value + "]."
+ " Reverting to default [" + MessageProperties.IO_DEFAULT_BUFFER_SIZE + "].",
+ " Reverting to default [at JRE's discretion].",
e);
}
}
return MessageProperties.IO_DEFAULT_BUFFER_SIZE;
return -1;
}

private static int getBufferSize() {
final int ioBufferSize = getIOBufferSize();
return ioBufferSize == -1 ? MessageProperties.IO_DEFAULT_BUFFER_SIZE : ioBufferSize;
}

private static boolean getAutosizeBuffer() {
return getIOBufferSize() == -1;
}

/**
Expand All @@ -93,6 +107,11 @@ private static int getBufferSize() {
* @throws IOException if there is an error reading or writing bytes.
*/
public static void writeTo(InputStream in, OutputStream out) throws IOException {
if (AUTOSIZE_BUFFER) {
in.transferTo(out);
return;
}

int read;
final byte[] data = new byte[BUFFER_SIZE];
while ((read = in.read(data)) != -1) {
Expand All @@ -108,6 +127,11 @@ public static void writeTo(InputStream in, OutputStream out) throws IOException
* @throws IOException if there is an error reading or writing characters.
*/
public static void writeTo(Reader in, Writer out) throws IOException {
if (AUTOSIZE_BUFFER) {
in.transferTo(out);
return;
}

int read;
final char[] data = new char[BUFFER_SIZE];
while ((read = in.read(data)) != -1) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2023 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018 Payara Foundation and/or its affiliates.
*
* This program and the accompanying materials are made available under the
Expand Down Expand Up @@ -66,7 +66,6 @@
import org.glassfish.jersey.message.MessageBodyWorkers;
import org.glassfish.jersey.message.internal.MessageBodyFactory;
import org.glassfish.jersey.message.internal.MessagingBinders;
import org.glassfish.jersey.message.internal.NullOutputStream;
import org.glassfish.jersey.model.internal.ComponentBag;
import org.glassfish.jersey.model.internal.ManagedObjectsFinalizer;
import org.glassfish.jersey.model.internal.RankedComparator;
Expand Down Expand Up @@ -586,7 +585,7 @@ private static <T> void printProviders(final String title, final Iterable<T> pro
* @return response future.
*/
public Future<ContainerResponse> apply(final ContainerRequest requestContext) {
return apply(requestContext, new NullOutputStream());
return apply(requestContext, OutputStream.nullOutputStream());
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2024 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
Expand All @@ -22,7 +22,7 @@
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
Expand Down Expand Up @@ -155,7 +155,7 @@ private InputStream getInputStream(final String jarUrlString) throws IOException
return new URL(jarUrlString).openStream();
} catch (final MalformedURLException e) {
return Files.newInputStream(
Paths.get(UriComponent.decode(jarUrlString, UriComponent.Type.PATH)));
Path.of(UriComponent.decode(jarUrlString, UriComponent.Type.PATH)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,7 @@ public static File createJarFile(final String name, final Suffix s, final String

final InputStream f = new BufferedInputStream(
Files.newInputStream(new File(base, entry.getKey()).toPath()));
final byte[] buf = new byte[1024];
int read = 1024;
while ((read = f.read(buf, 0, read)) != -1) {
jos.write(buf, 0, read);
}
f.transferTo(jos);
jos.closeEntry();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
Expand Down Expand Up @@ -114,7 +114,7 @@ private int countJarEntriesByPattern(final Pattern pattern) throws IOException {
private int countJarEntriesUsingScanner(final String parent, final boolean recursive) throws IOException {
int scannedEntryCount = 0;

try (final InputStream jaxRsApi = Files.newInputStream(Paths.get(this.jaxRsApiPath))) {
try (final InputStream jaxRsApi = Files.newInputStream(Path.of(this.jaxRsApiPath))) {
final JarFileScanner jarFileScanner = new JarFileScanner(jaxRsApi, parent, recursive);
while (jarFileScanner.hasNext()) {
// Fetch next entry.
Expand All @@ -136,7 +136,7 @@ private int countJarEntriesUsingScanner(final String parent, final boolean recur
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testClassEnumerationWithNonexistentPackage(final boolean recursive) throws IOException {
try (final InputStream jaxRsApi = Files.newInputStream(Paths.get(this.jaxRsApiPath))) {
try (final InputStream jaxRsApi = Files.newInputStream(Path.of(this.jaxRsApiPath))) {
final JarFileScanner jarFileScanner = new JarFileScanner(jaxRsApi, "jakarta/ws/r", recursive);
assertFalse(jarFileScanner.hasNext(), "Unexpectedly found package 'jakarta.ws.r' in jakarta.ws.rs-api");
}
Expand All @@ -145,7 +145,7 @@ public void testClassEnumerationWithNonexistentPackage(final boolean recursive)
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testClassEnumerationWithClassPrefix(final boolean recursive) throws IOException {
try (final InputStream jaxRsApi = Files.newInputStream(Paths.get(this.jaxRsApiPath))) {
try (final InputStream jaxRsApi = Files.newInputStream(Path.of(this.jaxRsApiPath))) {
final JarFileScanner jarFileScanner = new JarFileScanner(jaxRsApi, "jakarta/ws/rs/GE", recursive);
assertFalse(jarFileScanner.hasNext(), "Unexpectedly found package 'jakarta.ws.rs.GE' in jakarta.ws.rs-api");
}
Expand Down
4 changes: 2 additions & 2 deletions docs/src/main/docbook/media.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1753,8 +1753,8 @@ final Response response = target.request().post(entity);

<programlisting language="java">// MediaType of the body part will be derived from the file.
final List&lt;EntityPart&gt; multiPartEntity = new List&lt;&gt;();
list.add(EntityPart.withFileName("file001.txt").content(new FileInputStream("file001.txt")).build());
list.add(EntityPart.withFileName("mypom.xml").content(new FileInputStream("pom.xml")).build());
list.add(EntityPart.withFileName("file001.txt").content(Files.newInputStream(Path.of("file001.txt"))).build());
list.add(EntityPart.withFileName("mypom.xml").content(Files.newInputStream(Path.of("pom.xml"))).build());

final GenericEntity&lt;List&lt;EntityPart&gt;&gt; genericEntity = new GenericEntity&lt;&gt;(list) {};
final Entity entity = Entity.entity(genericEntity, MediaType.MULTIPART_FORM_DATA_TYPE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

Expand Down Expand Up @@ -145,7 +145,7 @@ public static void main(final String[] args) throws Exception {
private static void loadSettings() {
InputStream st = null;
try {
st = Files.newInputStream(Paths.get(PROPERTIES_FILE_NAME));
st = Files.newInputStream(Path.of(PROPERTIES_FILE_NAME));
PROPERTIES.load(st);
} catch (final IOException e) {
// ignore
Expand Down Expand Up @@ -178,7 +178,7 @@ private static void loadSettings() {
private static void storeSettings() {
OutputStream st = null;
try {
st = Files.newOutputStream(Paths.get(PROPERTIES_FILE_NAME));
st = Files.newOutputStream(Path.of(PROPERTIES_FILE_NAME));
PROPERTIES.store(st, null);
} catch (final IOException e) {
// ignore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -228,7 +228,7 @@ private void updatePermissionsFromFile() throws IOException {

try {

final BufferedReader reader = Files.newBufferedReader(Paths.get(felixPolicy));
final BufferedReader reader = Files.newBufferedReader(Path.of(felixPolicy));
String line;
final Set<String> cpiNames = new HashSet<String>();

Expand Down
Loading

0 comments on commit 21668db

Please sign in to comment.