了解 Java NIO Socket Channel 中 NullPointerException 的原因
我使用 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.NullPointerExceptionat 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜测 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.
ServerSocketChannel
的 Javadoc 说:您确定
ssc.accept()
不会因为这个原因返回null
吗?The Javadoc for
ServerSocketChannel
says:Are you sure
ssc.accept()
isn't returningnull
for just that reason?正如@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.