Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8316156: ByteArrayInputStream.transferTo causes MaxDirectMemorySize overflow #15733

Closed
wants to merge 6 commits into from

Conversation

bplb
Copy link
Member

@bplb bplb commented Sep 14, 2023

ByteArrayInputStream.transferTo invoked with an OutputStream parameter which delegates to a FileChannel throws an OutOfMemoryError if the length of the byte[] wrapped by the ByteArrayInputStream exceeds MaxDirectMemorySize. This is because FileChannel.write uses IOUtil.write which creates a temporary direct buffer for writing. If the byte[] length is larger than MaxDirectMemorySize, then the temporary direct buffer allocation fails with an OutOfMemoryError.


Progress

  • Change must be properly reviewed (1 review required, with at least 1 Reviewer)
  • Change must not contain extraneous whitespace
  • Commit message must refer to an issue

Issue

  • JDK-8316156: ByteArrayInputStream.transferTo causes MaxDirectMemorySize overflow (Bug - P4)

Reviewers

Reviewing

Using git

Checkout this PR locally:
$ git fetch https://git.openjdk.org/jdk.git pull/15733/head:pull/15733
$ git checkout pull/15733

Update a local copy of the PR:
$ git checkout pull/15733
$ git pull https://git.openjdk.org/jdk.git pull/15733/head

Using Skara CLI tools

Checkout this PR locally:
$ git pr checkout 15733

View PR using the GUI difftool:
$ git pr show -t 15733

Using diff file

Download this PR as a diff file:
https://git.openjdk.org/jdk/pull/15733.diff

Webrev

Link to Webrev Comment

@bridgekeeper
Copy link

bridgekeeper bot commented Sep 14, 2023

👋 Welcome back bpb! A progress list of the required criteria for merging this PR into master will be added to the body of your pull request. There are additional pull request commands available for use with this pull request.

@openjdk openjdk bot added the rfr Pull request is ready for review label Sep 14, 2023
@openjdk
Copy link

openjdk bot commented Sep 14, 2023

@bplb The following label will be automatically applied to this pull request:

  • nio

When this pull request is ready to be reviewed, an "RFR" email will be sent to the corresponding mailing list. If you would like to change these labels, use the /label pull request command.

@openjdk openjdk bot added the nio nio-dev@openjdk.org label Sep 14, 2023
@bplb bplb changed the title 8316156: (ch) Channels.newOutputStream(ch).write(bigByteArray) allocates alot of direct memory 8316156: (ch) Channels.newOutputStream(ch).write(bigByteArray) allocates a lot of direct memory Sep 14, 2023
@mlbridge
Copy link

mlbridge bot commented Sep 14, 2023

Webrevs

@@ -46,7 +46,7 @@
* @author Mark Reinhold
*/
class ChannelInputStream extends InputStream {
private static final int DEFAULT_BUFFER_SIZE = 8192;
static final int DEFAULT_BUFFER_SIZE = 8192;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this buffer size is now being used in more places, is it worth testing with 16KiB to match InputStream from #11783?

Suggested change
static final int DEFAULT_BUFFER_SIZE = 8192;
static final int DEFAULT_BUFFER_SIZE = 16384;

private static final int DEFAULT_BUFFER_SIZE = 16384;

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can look into running a benchmark on this.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A quick measurement suggests that doubling the buffer size to 16384 would increase read throughput by more than 15%, and write throughput by more than 40%.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be a nice additional benefit on top of reducing the direct memory allocations

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it’s still slower than uncapped. Brian mentioned only 8k vs 16k, not bigger or unconstrained. (And it also depends on the physical drivers below the test system)

@bplb
Copy link
Member Author

bplb commented Sep 14, 2023

Perhaps the test should be refactored to test read and write separately?

@vyommani
Copy link
Contributor

Perhaps the test should be refactored to test read and write separately?

that's good idea, separating read and write will make individual test's more readable/ maintainable.

pos += n;
rem -=n;
}
return nread;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still looks like a "read fully", I don't think we should have a loop here.

Copy link
Member Author

@bplb bplb Sep 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So at most Streams.DEFAULT_BUFFER_SIZE bytes would be read per call?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, something like Streams.MAX_BUFFER_SIZE = 128*1024, or whatever is good value.

if (rem <= 0)
return 0;

bb.limit(pos + Integer.min(rem, Streams.DEFAULT_BUFFER_SIZE));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume we would end up with a MAX_BUFFER_SIZE that is something like 128k, like we ended up in NioSocketImpl for the same reason. In order words, it's different to the chunk size that is DEFAULT_BUFFER_SIZE today.

Copy link

@pwagland pwagland Sep 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, getting back to the reason that this was created in the first place, namely that it is possible to limit MaxDirectBufferSize, ideally this limit could be dependent on how much is actually available in the system. Bits doesn't currently have any way to expose that. In the scenario that I was dealing with, I had 28M of direct buffer, but the system was trying to allocate (roughly) 62M, and that didn't work. So limiting to 128K would still work perfectly in that scenario.

try (InputStream in = new FileInputStream(path.toFile())) {
byte[] dst = new byte[SIZE];
int n = -1;
if ((n = in.read(dst)) != SIZE)
Copy link
Contributor

@vyommani vyommani Sep 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in.read(dst) may return less then the requested(SIZE in this test) ?. Can you please add little bit more descriptive 'RuntimeException' message . It will help to debug issue faster if it fails in future.

@bplb
Copy link
Member Author

bplb commented Sep 18, 2023

In 7ee65b9 the Channel{In,Out}putStream changes are reverted and similar changes are implemented in transferTo for BufferedInputStream and ByteArrayInputStream. In retrospect, I doubt that the BufferedInputStream changes and concomitant test code are needed.

@AlanBateman
Copy link
Contributor

Changing BAIS and BIS is good as it avoids the behavioural change that CIS.read may do a short read. The updates look okay but I think we'll need to expand the test for BIS.transferTo for cases where the BIS is created with a buffer size > 128k. Confining the change to just BAIS and not touching BIS is okay too.

One other thing is that the JBS issue and PR title/description are now out of date so probably should fix those up to avoid any confusion.

@pwagland
Copy link

pwagland commented Sep 19, 2023

In 7ee65b9 the Channel{In,Out}putStream changes are reverted and similar changes are implemented in transferTo for BufferedInputStream and ByteArrayInputStream. In retrospect, I doubt that the BufferedInputStream changes and concomitant test code are needed.

Doesn't this just fix only the reported problem though? If there is a InputStream out there that that can also drop a large buffer in, or even if there is code that just does a channelOutputStream.write(largeBuffer), that this will still fail?

The main issue that I had when I reported the problem is that I can no longer safely use Files.copy, since it relies on the passedInputStream only doing "small" writes, at least in the face of a limited DirectMemory allocation. This fixes the particular InputStream that I was using, but doesn't fix the generic problem, which means that Files.copy is still unsafe?

@AlanBateman
Copy link
Contributor

Doesn't this just fix only the reported problem though? If there is a InputStream out there that that can also drop a large buffer in, or even if there is code that just does a channelOutputStream.write(largeBuffer), that this will still fail?

The main issue that I had when I reported the problem is that I can no longer safely use Files.copy, since it relies on the passedInputStream only doing "small" writes, at least in the face of a limited DirectMemory allocation. This fixes the particular InputStream that I was using, but doesn't fix the generic problem, which means that Files.copy is still unsafe?

There's a compatibility impact to changing the channel read/write implementations to limit direct buffer usage when called with a heap based ByteBuffer that contains a large number of bytes. We have to be very cautious about changing anything there as it will break existing broken code that assumes a short read/write is not possible. We found two cases in the JDK, one is fixed, the other is WIP. Changing the adaptor class used by Channels.newInputStream has the same concern. I talked to @bplb off-list about this and we agreed that it requires a lot more thinking about changing anything.

As regards Files.copy(InputStream, Path). It uses the input stream's transferTo method to transfer the bytes to the target file. It could be changed to write in chunks or the input streams that have all bytes in the heap could write in chunks. One or both is okay and doesn't have compatibility concerns.

@pwagland
Copy link

As regards Files.copy(InputStream, Path). It uses the input stream's transferTo method to transfer the bytes to the target file. It could be changed to write in chunks or the input streams that have all bytes in the heap could write in chunks. One or both is okay and doesn't have compatibility concerns.

Thanks for this answer. The challenge is that we are very dependent on the specific implementation of the input streams transferTo method. Specifically, the default implementation is perfectly fine, the one in (the old) BAIS caused us issues.

If I understand correctly though, after this PR you can just wrap any InputStream into a BIS, and it would be safe, right? Maybe this is something that could be put into Files.copy? Then Files.copy would always work, and you aren't changing the short read/write characteristics?

@AlanBateman
Copy link
Contributor

Thanks for this answer. The challenge is that we are very dependent on the specific implementation of the input streams transferTo method. Specifically, the default implementation is perfectly fine, the one in (the old) BAIS caused us issues.

The BAIS.transferTo implementation was a bit naive so it's useful to re-visit this.

@pwagland
Copy link

If I understand correctly though, after this PR you can just wrap any InputStream into a BIS, and it would be safe, right? Maybe this is something that could be put into Files.copy? Then Files.copy would always work, and you aren't changing the short read/write characteristics?

Would it make sense to also do this, to ensure that Files.copy doesn't fail, regardless of what the input InputStream does?

@bplb
Copy link
Member Author

bplb commented Sep 19, 2023

Would it make sense to also do this, to ensure that Files.copy doesn't fail, regardless of what the input InputStream does?

It would make sense to clamp the uses of transferTo in Files.copy to a maximum chunk size, but I don't think wrapping in a ByteArrayInputStream is the way to go.

@bplb
Copy link
Member Author

bplb commented Sep 19, 2023

It would make sense to clamp the uses of transferTo in Files.copy to a maximum chunk size [...]

The problem with chunking InputStream.transferTo here is that it might seriously compromise performance when the IS is backed by a FileChannel.

@bplb bplb changed the title 8316156: (ch) Channels.newOutputStream(ch).write(bigByteArray) allocates a lot of direct memory 8316156: ByteArrayInputStream.transferTo causes MaxDirectMemorySize overflow Sep 19, 2023
@bplb
Copy link
Member Author

bplb commented Sep 19, 2023

This PR is now limited to ByteArrayInputStream. The use of InputStream.transferTo in Files.copy(InputStream,Path) and Files.copy(Path,Outputstream) can be investigated in the context of a different issue.

Copy link
Contributor

@AlanBateman AlanBateman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change to BAIS.tranfserTo write at most 128k at a time looks okay. The test looks okay and I assume you've checked the test is stable with 5Mb.

The PR description is a bit outdated now, I assume you can edit that so it aligns with what this change is about.

@openjdk
Copy link

openjdk bot commented Sep 20, 2023

@bplb This change now passes all automated pre-integration checks.

ℹ️ This project also has non-automated pre-integration requirements. Please see the file CONTRIBUTING.md for details.

After integration, the commit message for the final commit will be:

8316156: ByteArrayInputStream.transferTo causes MaxDirectMemorySize overflow

Reviewed-by: alanb

You can use pull request commands such as /summary, /contributor and /issue to adjust it as needed.

At the time when this comment was updated there had been 109 new commits pushed to the master branch:

  • 3301fb1: 8315869: UseHeavyMonitors not used
  • 54028e7: 8316562: serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java times out after JDK-8314829
  • 7c991cc: 8296246: Update Unicode Data Files to Version 15.1.0
  • a021dbc: 8316149: Open source several Swing JTree JViewport KeyboardManager tests
  • 455cfae: 8315880: change LockingMode default from LM_LEGACY to LM_LIGHTWEIGHT
  • 9e00949: 8316427: Duplicated code for {obj,type}ArrayKlass::array_klass
  • c43ebd3: 8315981: Opensource five more random Swing tests
  • e30e356: 8316461: Fix: make test outputs TEST SUCCESS after unsuccessful exit
  • 242eeae: 8286757: adlc tries to build with /pathmap but without /experimental:deterministic
  • b275bdd: 8308995: Update Network IO JFR events to be static mirror events
  • ... and 99 more: https://git.openjdk.org/jdk/compare/3b0a6d2a6842962218b8cebcd9c0672cb4ee6720...master

As there are no conflicts, your changes will automatically be rebased on top of these commits when integrating. If you prefer to avoid this automatic rebasing, please check the documentation for the /integrate command for further details.

➡️ To integrate this PR with the above commit message to the master branch, type /integrate in a new comment.

@openjdk openjdk bot added the ready Pull request is ready to be integrated label Sep 20, 2023
@bplb
Copy link
Member Author

bplb commented Sep 20, 2023

The test looks okay and I assume you've checked the test is stable with 5Mb.

I have not seen any problems but am running more tests before integrating.

The PR description is a bit outdated now, I assume you can edit that so it aligns with what this change is about.

I will update it.

@bplb
Copy link
Member Author

bplb commented Sep 20, 2023

I have not seen any problems but am running more tests before integrating.

50 repeats of the test on the usual four platforms succeeded.

@bplb
Copy link
Member Author

bplb commented Sep 20, 2023

/integrate

@openjdk
Copy link

openjdk bot commented Sep 20, 2023

Going to push as commit 5cacf21.
Since your change was applied there have been 110 commits pushed to the master branch:

  • 3461c7b: 8316532: Native library copying in BuildMicrobenchmark.gmk cause dups on macOS
  • 3301fb1: 8315869: UseHeavyMonitors not used
  • 54028e7: 8316562: serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java times out after JDK-8314829
  • 7c991cc: 8296246: Update Unicode Data Files to Version 15.1.0
  • a021dbc: 8316149: Open source several Swing JTree JViewport KeyboardManager tests
  • 455cfae: 8315880: change LockingMode default from LM_LEGACY to LM_LIGHTWEIGHT
  • 9e00949: 8316427: Duplicated code for {obj,type}ArrayKlass::array_klass
  • c43ebd3: 8315981: Opensource five more random Swing tests
  • e30e356: 8316461: Fix: make test outputs TEST SUCCESS after unsuccessful exit
  • 242eeae: 8286757: adlc tries to build with /pathmap but without /experimental:deterministic
  • ... and 100 more: https://git.openjdk.org/jdk/compare/3b0a6d2a6842962218b8cebcd9c0672cb4ee6720...master

Your commit was automatically rebased without conflicts.

@openjdk openjdk bot added the integrated Pull request has been integrated label Sep 20, 2023
@openjdk openjdk bot closed this Sep 20, 2023
@openjdk openjdk bot removed ready Pull request is ready to be integrated rfr Pull request is ready for review labels Sep 20, 2023
@openjdk
Copy link

openjdk bot commented Sep 20, 2023

@bplb Pushed as commit 5cacf21.

💡 You may see a message that your pull request was closed with unmerged commits. This can be safely ignored.

@bplb bplb deleted the Channels-newOutputStream-8316156 branch September 22, 2023 17:21
@pwagland
Copy link

pwagland commented Sep 28, 2023

@blpb / @AlanBateman : Do you know if this will this also be released to Java 17 and/or Java 21 service packs?

@pwagland
Copy link

@blpb / @AlanBateman : Do you know if this will this also be released to Java 17 and/or Java 21 service packs?

PR #227 is for Java 21, so it looks like at least Java 21. Here's hoping also for Java 17 :-)

@AlanBateman
Copy link
Contributor

@blpb / @AlanBateman : Do you know if this will this also be released to Java 17 and/or Java 21 service packs?

PR #227 is for Java 21, so it looks like at least Java 21. Here's hoping also for Java 17 :-)

This is not the place to lobby for back ports, I think you are looking for jdk-updates-dev.

@bplb
Copy link
Member Author

bplb commented Oct 18, 2023

PR #227 is for Java 21, so it looks like at least Java 21.

I think you intended openjdk/jdk21u#227.

Here's hoping also for Java 17 :-)

I already labelled the issue as being desirable for JDK 17 so it should be on the radar. As @AlanBateman indicated, you can lobby for that on jdk-updates-dev

@zde
Copy link

zde commented Mar 15, 2024

because FileChannel.write uses IOUtil.write which creates a temporary direct buffer for writing

Why are you "fixing" ByteArrayInputStream.writeTo when the problem is elsewhere?
IOUtil.write should create a reasonably sized buffer and reuse it instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
integrated Pull request has been integrated nio nio-dev@openjdk.org
8 participants