Skip to content

Commit 73beab6

Browse files
committed
Connections dont always get cleaned up after lost connection
see TooTallNate#504
1 parent fa3c5c0 commit 73beab6

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

src/main/java/org/java_websocket/AbstractWebSocket.java

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
import org.java_websocket.framing.CloseFrame;
2929

30+
import java.util.ArrayList;
3031
import java.util.Collection;
3132
import java.util.Timer;
3233
import java.util.TimerTask;
@@ -104,23 +105,30 @@ protected void startConnectionLostTimer() {
104105
cancelConnectionLostTimer();
105106
connectionLostTimer = new Timer();
106107
connectionLostTimerTask = new TimerTask() {
108+
109+
/**
110+
* Keep the connections in a separate list to not cause deadlocks
111+
*/
112+
private ArrayList<WebSocket> connections = new ArrayList<WebSocket>( );
107113
@Override
108114
public void run() {
109-
Collection<WebSocket> con = connections();
110-
synchronized ( con ) {
111-
long current = (System.currentTimeMillis()-(connectionLostTimeout * 1500));
112-
for( WebSocket conn : con ) {
113-
if (conn instanceof WebSocketImpl) {
114-
if( ((WebSocketImpl)conn).getLastPong() < current ) {
115-
if (WebSocketImpl.DEBUG)
116-
System.out.println("Closing connection due to no pong received: " + conn.toString());
117-
conn.close( CloseFrame.ABNORMAL_CLOSE );
118-
} else {
119-
conn.sendPing();
120-
}
121-
}
122-
}
123-
}
115+
connections.clear();
116+
connections.addAll( connections() );
117+
long current = (System.currentTimeMillis()-(connectionLostTimeout * 1500));
118+
WebSocketImpl webSocketImpl;
119+
for( WebSocket conn : connections ) {
120+
if (conn instanceof WebSocketImpl) {
121+
webSocketImpl = (WebSocketImpl)conn;
122+
if( webSocketImpl.getLastPong() < current ) {
123+
if (WebSocketImpl.DEBUG)
124+
System.out.println("Closing connection due to no pong received: " + conn.toString());
125+
webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE , false );
126+
} else {
127+
webSocketImpl.sendPing();
128+
}
129+
}
130+
}
131+
connections.clear();
124132
}
125133
};
126134
connectionLostTimer.scheduleAtFixedRate( connectionLostTimerTask,connectionLostTimeout * 1000, connectionLostTimeout * 1000 );

0 commit comments

Comments
 (0)