Skip to content

Commit

Permalink
fix: fix fd isn't released manually when download finished which may …
Browse files Browse the repository at this point in the history
…raise oom on case of there are many tasks running one by one
  • Loading branch information
Jacksgong committed Apr 20, 2018
1 parent 29e04a7 commit 25ddd76
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,25 @@ public class DownloadUriOutputStream implements DownloadOutputStream {
@NonNull private final FileChannel channel;
@NonNull private final ParcelFileDescriptor pdf;
@NonNull private final BufferedOutputStream out;
@NonNull private final FileOutputStream fos;

public DownloadUriOutputStream(Context context, Uri uri, int bufferSize) throws
FileNotFoundException {
final ParcelFileDescriptor pdf = context.getContentResolver().openFileDescriptor(uri, "rw");
if (pdf == null) throw new FileNotFoundException("result of " + uri + " is null!");
this.pdf = pdf;

final FileOutputStream fos = new FileOutputStream(pdf.getFileDescriptor());
channel = fos.getChannel();
out = new BufferedOutputStream(fos, bufferSize);
this.fos = new FileOutputStream(pdf.getFileDescriptor());
this.channel = fos.getChannel();
this.out = new BufferedOutputStream(fos, bufferSize);
}

DownloadUriOutputStream(@NonNull FileChannel channel, @NonNull ParcelFileDescriptor pdf,
@NonNull FileOutputStream fos,
@NonNull BufferedOutputStream out) {
this.channel = channel;
this.pdf = pdf;
this.fos = fos;
this.out = out;
}

Expand All @@ -64,6 +67,7 @@ public void write(byte[] b, int off, int len) throws IOException {
@Override
public void close() throws IOException {
out.close();
fos.close();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.SyncFailedException;
import java.nio.channels.FileChannel;

Expand All @@ -46,6 +47,7 @@ public class DownloadUriOutputStreamTest {
@Mock private FileChannel channel;
@Mock private ParcelFileDescriptor pdf;
@Mock private BufferedOutputStream out;
@Mock private FileOutputStream fos;
@Mock private FileDescriptor fd;

private DownloadUriOutputStream outputStream;
Expand All @@ -54,7 +56,7 @@ public class DownloadUriOutputStreamTest {
public void setup() {
initMocks(this);

outputStream = new DownloadUriOutputStream(channel, pdf, out);
outputStream = new DownloadUriOutputStream(channel, pdf, fos, out);
}

@Test
Expand All @@ -68,6 +70,7 @@ public void write() throws Exception {
public void close() throws Exception {
outputStream.close();
verify(out).close();
verify(fos).close();
}

@Rule
Expand Down

0 comments on commit 25ddd76

Please sign in to comment.