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

Should I call flush before closing when using ZstdOutputStream? #335

Open
ConeyLiu opened this issue Nov 29, 2024 · 1 comment
Open

Should I call flush before closing when using ZstdOutputStream? #335

ConeyLiu opened this issue Nov 29, 2024 · 1 comment

Comments

@ConeyLiu
Copy link

Hopefully, someone could help on whether we should call flush before closing a ZstdOuputStream? Because this could produce different behavior.

    // compress without flush
    byte[] bytes1 = null;
    ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
    try(ByteArrayOutputStream out = outputStream1;
        ZstdOutputStream zstd = new ZstdOutputStream(out, 3)) {
      zstd.setWorkers(0);

      zstd.write(0);
    }

    bytes1 = outputStream1.toByteArray();
    
    // compress with flush
    byte[] bytes2 = null;
    ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
    try(ByteArrayOutputStream out = outputStream2;
        ZstdOutputStream zstd = new ZstdOutputStream(out, 3)) {
      zstd.setWorkers(0);

      zstd.write(0);

      zstd.flush(); // flush before close
    }

    bytes2 = outputStream2.toByteArray();

    Arrays.equals(bytes1, bytes2);

Call flush could produce extra 3 bytes:
企业微信截图_f8d99e89-c545-482b-8539-d4f821ac121c

@ConeyLiu ConeyLiu changed the title Whether call flush before closing a ZstdOutputStream generates a different result Should I call flush before closing when using ZstdOutputStream? Nov 29, 2024
@luben
Copy link
Owner

luben commented Dec 1, 2024

Closing the stream makes sure all the data is flushed downstream, so you don't need to flush it before that.

You need to call flush only if you have nor finished writing to the stream but want to make sure that all written data is propagated downstream.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants