Skip to content

Commit

Permalink
Fixed null pointer regression in native code
Browse files Browse the repository at this point in the history
This occurred due to the fix for #3726 which allowed the GC to collect the output/input streams before the socket itself was collected
  • Loading branch information
shai-almog committed Nov 4, 2023
1 parent d3f5b30 commit 8bc1dcc
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions CodenameOne/src/com/codename1/io/Socket.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@
* @author Shai Almog
*/
public class Socket {
/**
* Keeping member field so the GC won't collect these objects before the socket itself is collected.
* This can cause a problem since there's native reliance on these objects.
*/
private SocketInputStream input;
private SocketOutputStream output;

private Socket() {}

/**
Expand Down Expand Up @@ -74,7 +81,9 @@ public void run() {
Object connection = Util.getImplementation().connectSocket(host, port, sc.getConnectTimeout());
if(connection != null) {
sc.setConnected(true);
sc.connectionEstablished(new SocketInputStream(connection, sc), new SocketOutputStream(connection, sc));
sc.input = new SocketInputStream(connection, sc);
sc.output = new SocketOutputStream(connection, sc);
sc.connectionEstablished(sc.input, sc.output);
} else {
sc.setConnected(false);
if(connection == null) {
Expand Down Expand Up @@ -107,8 +116,9 @@ public void run() {
connection[0] = Util.getImplementation().connectSocket(host, port, sc.getConnectTimeout());
if(connection[0] != null) {
sc.setConnected(true);
sc.connectionEstablished(new SocketInputStream(connection[0], sc),
new SocketOutputStream(connection[0], sc));
sc.input = new SocketInputStream(connection[0], sc);
sc.output = new SocketOutputStream(connection[0], sc);
sc.connectionEstablished(sc.input, sc.output);
} else {
sc.setConnected(false);
if(connection[0] == null) {
Expand All @@ -130,6 +140,8 @@ public void close() throws IOException {
throw new RuntimeException(e.getMessage());
}
}
input = null;
output = null;
if(Util.getImplementation().isSocketConnected(connection[0])) {
Util.getImplementation().disconnectSocket(connection[0]);
}
Expand Down Expand Up @@ -158,7 +170,9 @@ public void run() {
sc.setConnected(true);
Display.getInstance().startThread(new Runnable() {
public void run() {
sc.connectionEstablished(new SocketInputStream(connection, sc), new SocketOutputStream(connection, sc));
sc.input = new SocketInputStream(connection, sc);
sc.output = new SocketOutputStream(connection, sc);
sc.connectionEstablished(sc.input, sc.output);
sc.setConnected(false);
}
}, "Connection " + port).start();
Expand Down

0 comments on commit 8bc1dcc

Please sign in to comment.