Skip to content

Fixing a Thread Leak in Database Client Code (Related to #29) #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 28 additions & 23 deletions src/main/java/com/google/firebase/database/tubesock/WebSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package com.google.firebase.database.tubesock;

import static com.google.common.base.Preconditions.checkState;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
Expand Down Expand Up @@ -64,7 +66,7 @@ public void setName(Thread t, String name) {
private final WebSocketWriter writer;
private final WebSocketHandshake handshake;
private final int clientId = clientCount.incrementAndGet();
private final Thread innerThread;
private Thread innerThread;
private volatile State state = State.NONE;
private volatile Socket socket = null;
private WebSocketEventHandler eventHandler = null;
Expand Down Expand Up @@ -99,15 +101,6 @@ public WebSocket(URI url, String protocol) {
* if not extra headers are requested
*/
public WebSocket(URI url, String protocol, Map<String, String> extraHeaders) {
innerThread =
getThreadFactory()
.newThread(
new Runnable() {
@Override
public void run() {
runReader();
}
});
this.url = url;
handshake = new WebSocketHandshake(url, protocol, extraHeaders);
receiver = new WebSocketReceiver(this);
Expand Down Expand Up @@ -150,9 +143,23 @@ public synchronized void connect() {
close();
return;
}
getIntializer().setName(getInnerThread(), THREAD_BASE_NAME + "Reader-" + clientId);
state = State.CONNECTING;
getInnerThread().start();
start();
}

private synchronized void start() {
checkState(innerThread == null, "Inner thread already started");
innerThread =
getThreadFactory()
.newThread(
new Runnable() {
@Override
public void run() {
runReader();
}
});
getIntializer().setName(innerThread, THREAD_BASE_NAME + "Reader-" + clientId);
innerThread.start();
}

/**
Expand Down Expand Up @@ -312,13 +319,15 @@ private Socket createSocket() {
* convenience method to make sure everything shuts down, if desired.
*/
public void blockClose() throws InterruptedException {
// If the thread is new, it will never run, since we closed the connection before we
// actually
// connected
if (writer.getInnerThread().getState() != Thread.State.NEW) {
writer.getInnerThread().join();
writer.waitForTermination();
Thread thread;
synchronized (this) {
if (innerThread == null) {
return;
}
thread = innerThread;
}
getInnerThread().join();
thread.join();
}

private void runReader() {
Expand Down Expand Up @@ -389,7 +398,7 @@ private void runReader() {
writer.setOutput(output);
receiver.setInput(input);
state = WebSocket.State.CONNECTED;
writer.getInnerThread().start();
writer.start();
eventHandler.onOpen();
receiver.run();
} catch (WebSocketException wse) {
Expand All @@ -402,10 +411,6 @@ private void runReader() {
}
}

Thread getInnerThread() {
return innerThread;
}

private enum State {
NONE,
CONNECTING,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ void run() {
this.eventHandler = websocket.getEventHandler();
while (!stop) {
try {
if (Thread.interrupted()) {
throw new InterruptedException();
}
int offset = 0;
offset += read(inputHeader, offset, 1);
boolean fin = (inputHeader[0] & 0x80) != 0;
Expand Down Expand Up @@ -94,6 +97,8 @@ void run() {
continue;
} catch (IOException ioe) {
handleError(new WebSocketException("IO Error", ioe));
} catch (InterruptedException e) {
handleError(new WebSocketException("Receiver interrupted", e));
} catch (WebSocketException e) {
handleError(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package com.google.firebase.database.tubesock;

import static com.google.common.base.Preconditions.checkState;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
Expand All @@ -32,26 +34,18 @@
class WebSocketWriter {

private final Random random = new Random();
private final Thread innerThread;
private final String threadName;

private Thread innerThread;
private BlockingQueue<ByteBuffer> pendingBuffers;
private volatile boolean stop = false;
private boolean closeSent = false;
private WebSocket websocket;
private WritableByteChannel channel;

WebSocketWriter(WebSocket websocket, String threadBaseName, int clientId) {
innerThread =
WebSocket.getThreadFactory()
.newThread(
new Runnable() {
@Override
public void run() {
runWriter();
}
});

WebSocket.getIntializer().setName(getInnerThread(), threadBaseName + "Writer-" + clientId);
this.websocket = websocket;
this.threadName = threadBaseName + "Writer-" + clientId;
pendingBuffers = new LinkedBlockingQueue<>();
}

Expand Down Expand Up @@ -166,7 +160,31 @@ private void runWriter() {
}
}

Thread getInnerThread() {
return innerThread;
synchronized void start() {
checkState(innerThread == null, "Inner thread already started");
innerThread =
WebSocket.getThreadFactory()
.newThread(
new Runnable() {
@Override
public void run() {
runWriter();
}
});
WebSocket.getIntializer().setName(innerThread, threadName);
innerThread.start();
}

void waitForTermination() throws InterruptedException {
// If the thread is null, it will never be instantiated, since we closed the connection
// before we actually connected.
Thread thread;
synchronized (this) {
if (innerThread == null) {
return;
}
thread = innerThread;
}
thread.join();
}
}