From c53f629d63f8579c37c680dc0051c5c5da1a95c2 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 28 Oct 2023 14:38:29 +0300 Subject: [PATCH] Another attempt to fix socket memory leak Ideally should fix both #3726 and the regression in #3753 --- CodenameOne/src/com/codename1/io/Socket.java | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/CodenameOne/src/com/codename1/io/Socket.java b/CodenameOne/src/com/codename1/io/Socket.java index 6ec54b5d90..79559af97c 100644 --- a/CodenameOne/src/com/codename1/io/Socket.java +++ b/CodenameOne/src/com/codename1/io/Socket.java @@ -211,11 +211,13 @@ public synchronized void reset() throws IOException { } @Override - public void close() throws IOException { - closed = true; - if(Util.getImplementation().isSocketConnected(impl)) { - Util.getImplementation().disconnectSocket(impl); - con.setConnected(false); + public synchronized void close() throws IOException { + if(!closed) { + closed = true; + if (Util.getImplementation().isSocketConnected(impl)) { + Util.getImplementation().disconnectSocket(impl); + con.setConnected(false); + } } } @@ -335,7 +337,7 @@ public int read() throws IOException { protected void finalize() throws Throwable { try { close(); - } catch (IOException err) { + } catch (Throwable err) { Log.e(err); } } @@ -350,8 +352,8 @@ static class SocketOutputStream extends OutputStream { } @Override - public void close() throws IOException { - if(Util.getImplementation().isSocketConnected(impl)) { + public synchronized void close() throws IOException { + if (con.isConnected() && Util.getImplementation().isSocketConnected(impl)) { Util.getImplementation().disconnectSocket(impl); con.setConnected(false); } @@ -397,7 +399,7 @@ public void write(int b) throws IOException { protected void finalize() throws Throwable { try { close(); - } catch (IOException err) { + } catch (Throwable err) { Log.e(err); } }