Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Memory leaks 如何使用Jetty 9 WebSocketClient在关闭线程时避免内存泄漏_Memory Leaks_Websocket_Jetty_Client - Fatal编程技术网

Memory leaks 如何使用Jetty 9 WebSocketClient在关闭线程时避免内存泄漏

Memory leaks 如何使用Jetty 9 WebSocketClient在关闭线程时避免内存泄漏,memory-leaks,websocket,jetty,client,Memory Leaks,Websocket,Jetty,Client,我们有一个使用Jetty WebSocketClient连接到服务器的工具。我们有时需要重新启动与服务器的连接。 使用当前代码,我们在org.eclipse.jetty.util.thread.ShutdownThread遇到内存泄漏,其中保存了org.eclipse.jetty.websocket.client.WebSocketClient的所有已用实例 在文档中,唯一要做的事情就是调用client.stop 代码或Jetty本身是否存在问题 下面是该代码的一个简单示例。其中main运行一个

我们有一个使用Jetty WebSocketClient连接到服务器的工具。我们有时需要重新启动与服务器的连接。 使用当前代码,我们在org.eclipse.jetty.util.thread.ShutdownThread遇到内存泄漏,其中保存了org.eclipse.jetty.websocket.client.WebSocketClient的所有已用实例

在文档中,唯一要做的事情就是调用client.stop

代码或Jetty本身是否存在问题

下面是该代码的一个简单示例。其中main运行一个测试,在该测试中跟踪和比较消耗的内存

结果是:使用了更多堆:97/100-告诉我有什么不对劲

任务处理与服务器的连接,并保留其他信息:

package example;

import java.io.IOException;
import java.net.URI;

import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;

class Task {

    public enum StopReason {

        CLOSED,

        EXIT,

        RESTART
    }

    private WebSocketClient client;

    private ClientSocket socket;

    private URI uri;

    public Task(URI uri) {
        this.uri = uri;
    }

    public void restart() throws IOException {
        System.out.println("Task.restart");
        stop(StopReason.RESTART);

        synchronized (this) {
            try {
                this.wait(10);
            } catch (InterruptedException e) {
                // ignore
            }
        }

        start();
    }

    public void start() throws IOException {
        System.out.println("Task.start");
        client = new WebSocketClient();
        client.getPolicy().setIdleTimeout(120000);
        client.setMaxIdleTimeout(1000);

        socket = new ClientSocket(this);

        try {
            client.start();
            System.out.println("Task started");
        } catch (Exception e) {
            throw new IOException("Failed to start WebSocketClient: " + e.getLocalizedMessage(), e);
        }

        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setRequestURI(uri);
        client.connect(socket, request.getRequestURI(), request);
        System.out.println("Task connected");
    }

    public void stop(Task.StopReason stopReason) throws IOException {
        System.out.println("Task.stop " + stopReason);

        if (stopReason != StopReason.CLOSED) {
            try {
                client.stop();
            } catch (Exception e) {
                throw new IOException("Task Error at 'stop': " + e.getLocalizedMessage(), e);
            }

            client.destroy();

            try {
                client.getConnectionManager().stop();
            } catch (Exception e) {
                System.err.println("Task Error at 'stop': " + e.getLocalizedMessage());
            }

            client.getConnectionManager().destroy();
        }

        System.out.println("Task.stop done " + stopReason);
    }
}
运行测试的主类:

package example;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Map;

import javax.websocket.DeploymentException;
import javax.websocket.server.ServerEndpoint;

import org.glassfish.tyrus.server.Server;

import example.Task.StopReason;

@SuppressWarnings("javadoc")
@ServerEndpoint(value = "/test")
public class MemoryLeakDebug {

    public static void main(String[] args) throws IOException, URISyntaxException, DeploymentException {
        Map<String, Object> config = Collections.emptyMap();
        Server server = new Server("localhost", 10000, "/test", config, DummyEndpoint.class);
        server.start();

        Task task = new Task(new URI("ws://localhost:10000/test/test"));
        task.start();

        long[] useds = new long[100];

        try {
            for (int i = 0; i < useds.length; i++) {
                System.out.println("------------------------");
                Runtime.getRuntime().gc();
                long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                System.out.println("used: " + used);
                useds[i] = used;

                task.restart();

                synchronized (task) {
                    try {
                        task.wait(100);
                    } catch (InterruptedException e) {
                        System.err.println(e.getLocalizedMessage());
                    }
                }
            }
        } catch (AssertionError e) {
            throw e;
        } finally {
            task.stop(StopReason.EXIT);
            server.stop();

            StringBuilder sb = new StringBuilder("useds:\n");
            int index = 0;
            int count = 0;
            int moreCount = 0;
            long last = -1;

            for (long used : useds) {
                sb.append((index++) + "\t" + used + "\n");

                if (used > 0) {
                    count++;
                }

                if (last != -1) {
                    if (used > last) {
                        moreCount++;
                    }
                }

                last = used;
            }

            System.out.println(sb.toString());
            System.out.println(moreCount + " / " + count);

            if (moreCount > count * .75) {
                throw new IllegalStateException("more heap used: " + moreCount + " / " + count);
            }
        }
    }
}
简化虚拟客户端:

package example;

import java.io.IOException;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

import example.Task.StopReason;

@SuppressWarnings("javadoc")
@WebSocket
public class ClientSocket {

    private Session session;
    private Task task;

    public ClientSocket(Task task) {
        this.task = task;
    }

    @OnWebSocketClose
    public void handleClose(int statusCode, String reason) {
        System.out.println("ClientSocket@OnWebSocketClose " + statusCode + " " + reason);
        session = null;

        try {
            task.stop(StopReason.CLOSED);
        } catch (IOException e) {
            throw new IllegalStateException("Error at 'handleClose': " + e.getLocalizedMessage(), e);
        }
    }

    @OnWebSocketConnect
    public void handleConnect(Session session) {
        System.out.println("ClientSocket@OnWebSocketConnect " + session);
        this.session = session;
    }

    @OnWebSocketError
    public void handleError(Throwable cause) {
        System.err.println("ClientSocket@OnError" + cause);
        cause.printStackTrace();
    }

    @OnWebSocketMessage
    public void handleMessage(String message) {
        System.out.println("ClientSocket@OnWebSocketMessage " + message);
    }

    public boolean isConnected() {
        return session != null;
    }
}
我们的依赖关系:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>example</groupId>
    <artifactId>WebSocketClientDebug</artifactId>
    <version>0.1.0-SNAPSHOT</version>

    <properties>
        <tyrus-version>[1.8.3,1.9)</tyrus-version>
    </properties>

    <dependencies>
        <!-- + + + + + external dependencies + + + + + -->
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-client</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>[2.6.0,3.2.0)</version>
        </dependency>

        <!-- + + + + + external test dependencies + + + + + -->
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-client</artifactId>
            <version>[1.8.3,1.9)</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-container-grizzly-server</artifactId>
            <version>${tyrus-version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-server</artifactId>
            <version>${tyrus-version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-container-grizzly-client</artifactId>
            <version>${tyrus-version}</version>
        </dependency>
    </dependencies>
</project>

这是Jetty WebSocketClient行为中的一个bug

Jetty 9.2.4目前正在进行此修复,正在测试中,并将在未来7天内发布


如果您想访问此分阶段版本,或只是等待它发布,请通过irc.freenode.net/jetty与我联系。

是的,此错误似乎就是问题所在。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>example</groupId>
    <artifactId>WebSocketClientDebug</artifactId>
    <version>0.1.0-SNAPSHOT</version>

    <properties>
        <tyrus-version>[1.8.3,1.9)</tyrus-version>
    </properties>

    <dependencies>
        <!-- + + + + + external dependencies + + + + + -->
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-client</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>[2.6.0,3.2.0)</version>
        </dependency>

        <!-- + + + + + external test dependencies + + + + + -->
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-client</artifactId>
            <version>[1.8.3,1.9)</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-container-grizzly-server</artifactId>
            <version>${tyrus-version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-server</artifactId>
            <version>${tyrus-version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-container-grizzly-client</artifactId>
            <version>${tyrus-version}</version>
        </dependency>
    </dependencies>
</project>