Skip to content

Commit

Permalink
Add finalize() method to ServerConnection and AndroidStatusNotifier. …
Browse files Browse the repository at this point in the history
…Prevent calling close() methods twice
  • Loading branch information
thevindu-w committed Apr 15, 2024
1 parent 67b2432 commit 28b8266
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ public abstract class ServerConnection {
protected OutputStream outStream;
protected InputStream inStream;
protected Socket socket;
private boolean closed;

protected ServerConnection() {
this.socket = null;
this.closed = false;
}

protected ServerConnection(Socket socket) {
Expand Down Expand Up @@ -79,9 +81,19 @@ public boolean receive(byte[] buffer) {
}

public void close() {
synchronized (this) {
if (this.closed) return;
this.closed = true;
}
try {
this.socket.close();
} catch (RuntimeException | IOException ignored) {
}
}

@Override
protected void finalize() throws Throwable {
this.close();
super.finalize();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class AndroidStatusNotifier implements StatusNotifier {
public final class AndroidStatusNotifier implements StatusNotifier {

private static final int PROGRESS_MAX = 100;
private final NotificationManagerCompat notificationManager;
Expand All @@ -38,6 +38,7 @@ public class AndroidStatusNotifier implements StatusNotifier {
private final int notificationId;
private int prev;
private long prevTime;
private boolean finished;

public AndroidStatusNotifier(
Activity activity,
Expand All @@ -56,6 +57,7 @@ public AndroidStatusNotifier(
this.notificationId = notificationId;
this.prev = -1;
this.prevTime = 0;
this.finished = false;
}

@Override
Expand Down Expand Up @@ -98,6 +100,10 @@ public void reset() {

@Override
public void finish() {
synchronized (this) {
if (this.finished) return;
this.finished = true;
}
try {
if (this.notificationManager != null) {
NotificationManagerCompat finalNotificationManager = this.notificationManager;
Expand All @@ -112,4 +118,10 @@ public void finish() {
} catch (Exception ignored) {
}
}

@Override
protected void finalize() throws Throwable {
this.finish();
super.finalize();
}
}

0 comments on commit 28b8266

Please sign in to comment.