了解 Java NIO Socket Channel 中 NullPointerException 的原因

发布于 2024-11-07 09:34:04 字数 1998 浏览 2 评论 0原文

我使用 java nio 组合了一个简单的 echo 类型服务器应用程序。虽然它能够写入数据,但它总是抛出以下异常。谁能解释为什么会发生这种情况?我的代码如下。在创建包含 run 方法的线程之前,我确保 key.isAcceptable() 为 true。

线程“pool-1-thread-2”中出现异常 java.lang.NullPointerException

ExecutorService pool = Executors.newFixedPool(5);
...
try {
    pool.execute(                                           
        new Thread() {
            @Override public void run() {
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = null;
                try {
                    sc = ssc.accept();
                    String response = "Server thread (" + Thread.currentThread().getId() + ") Current time: " + new Date();
                    ByteBuffer bytes = encoder.encode(CharBuffer.wrap(response));
                    sc.write(bytes);
                } catch (java.io.IOException e) {
                    System.out.println("Exception: " + e.getMessage());                                                                              
                } finally {
                    try {
                        if (sc.isOpen()) sc.close(); // This is the line causing the exception to be thrown. If the check is changed to (sc != null) no exceptions are thrown.
                    } catch (java.io.IOException e) {
                        System.out.println("Exception: " + e.getMessage());
                    }
                }
            }
        }
    );
} catch (java.lang.Exception e) {
    System.out.println("Interrupted!");
}               

线程“pool-1-thread-2”中出现异常 60java.lang.NullPointerException

 在 EchoServer$1.run(EchoServer.java:61)
    在 java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec

utor.java:886) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor .java:908) 在 java.lang.Thread.run(Thread.java:619)

I've put together a simple echo type server app using java nio. While it is able to write the data, it always throws the following exception. Can anyone explain why this is happening? My code is below. Before the thread containing the run method is created I ensure the key.isAcceptable() is true.

Exception in thread "pool-1-thread-2"
java.lang.NullPointerException

ExecutorService pool = Executors.newFixedPool(5);
...
try {
    pool.execute(                                           
        new Thread() {
            @Override public void run() {
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = null;
                try {
                    sc = ssc.accept();
                    String response = "Server thread (" + Thread.currentThread().getId() + ") Current time: " + new Date();
                    ByteBuffer bytes = encoder.encode(CharBuffer.wrap(response));
                    sc.write(bytes);
                } catch (java.io.IOException e) {
                    System.out.println("Exception: " + e.getMessage());                                                                              
                } finally {
                    try {
                        if (sc.isOpen()) sc.close(); // This is the line causing the exception to be thrown. If the check is changed to (sc != null) no exceptions are thrown.
                    } catch (java.io.IOException e) {
                        System.out.println("Exception: " + e.getMessage());
                    }
                }
            }
        }
    );
} catch (java.lang.Exception e) {
    System.out.println("Interrupted!");
}               

Exception in thread "pool-1-thread-2"
60java.lang.NullPointerException

    at EchoServer$1.run(EchoServer.java:61)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec

utor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:908)
at java.lang.Thread.run(Thread.java:619)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

趴在窗边数星星i 2024-11-14 09:34:04

我猜测 ssc.accept 返回的 SocketChannel 为 null,这又意味着 ServerSocketChannel 处于非阻塞模式并且没有挂起的连接。

I'd guess that the SocketChannel returned by ssc.accept is null, which in turn implies that the ServerSocketChannel is in non-blocking mode and there is no pending connection.

森林散布 2024-11-14 09:34:04

ServerSocketChannel 的 Javadoc 说:

If this channel is in non-blocking mode then this method will immediately 
return null if there are no pending connections. Otherwise it will block 
indefinitely until a new connection is available or an I/O error occurs.

您确定 ssc.accept() 不会因为这个原因返回 null 吗?

The Javadoc for ServerSocketChannel says:

If this channel is in non-blocking mode then this method will immediately 
return null if there are no pending connections. Otherwise it will block 
indefinitely until a new connection is available or an I/O error occurs.

Are you sure ssc.accept() isn't returning null for just that reason?

客…行舟 2024-11-14 09:34:04

正如@IainM和@QuantumMechanic所建议的,您没有检查“sc”是否为空。如果 NPE 出现在 sc.close() 中,“sc”为 null,我会说您有一个 NPE 调用 sc.write(),而在 finally{} 块中调用 sc.close() 则有另一个 NPE。

您也没有检查 write() 的结果,因此您可能只写了部分消息,或者实际上什么也没写。您还对 sc.isOpen() 进行了完全毫无意义的测试。这段代码中要么为 null,要么为 open,没有其他可能。

我不知道当它不读取任何输入时,如何将其称为回显服务器。

这不是使用 NIO 的方式。整个想法是您不需要额外的线程。你的整个设计有严重的问题。

你打印“Interrupted!”也是在欺骗自己。 任何异常,并通过不打印其消息或堆栈跟踪来隐藏实际异常。这也不是使用异常的方法。

As suggested by @IainM and @QuantumMechanic, you aren't checking 'sc' for null. If the NPE arises in sc.close(), 'sc' was null, I would say you got an NPE calling sc.write(), and another one in the finally{} block calling sc.close().

You also aren't checking the result of the write(), so you may be writing partial messages or indeed nothing at all. You also have a completely pointless test for sc.isOpen(). It is either null or open in this code, there is no other possibility.

And I don't know how you can call this thing an echo server when it doesn't read any input.

This is not the way to use NIO. The whole idea is that you don't need extra threads. There is something seriously wrong with your entire design.

You are also lying to yourself by printing "Interrupted!" on any exception, and concealing the actual exception by not printing its message or stack trace. This is not the way to use exceptions either.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文