Skip to content
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

RPC的暴露服务的代码不会创建无限多线程吗? #2

Open
ohMyJason opened this issue Jan 17, 2023 · 1 comment
Open

RPC的暴露服务的代码不会创建无限多线程吗? #2

ohMyJason opened this issue Jan 17, 2023 · 1 comment

Comments

@ohMyJason
Copy link

 /**
     * 暴漏服务
     * @param serviceImpl 服务的实现
     * @param port 服务所处的端口号
     */
    public static void export(Object serviceImpl, int port) {
        try {
            try (ServerSocket server = new ServerSocket(port)) {
                while (!Thread.currentThread().isInterrupted()) {
                    Socket socket = server.accept();
                    new Thread(() -> {
                        try (ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
                            Method method = serviceImpl.getClass().getMethod(in.readUTF(), (Class<?>[]) in.readObject());
                            Object result = method.invoke(serviceImpl, (Object[]) in.readObject());
                            try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
                                out.writeObject(result);
                            }
                            System.out.println("Invoke method [" + method.getName() + "()] success, form " + socket.getRemoteSocketAddress());
                        } catch (Exception e) {
                            throw new RuntimeException("Export service fail .", e);
                        }
                    }).start();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Export service fail .", e);
        }
        System.out.println("Export service " + serviceImpl.getClass().getSimpleName() + " success on port " + port);
    }

socket.accept的时候返回为null,下面就直接创建线程执行了。

@wei183366
Copy link

accpet不是阻塞机制吗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants