Chr*_*tof 3 java multithreading exception
我一直在研究这个问题好几个小时,我无法得到一个像样的解决方案或解释为什么这个异常(java.net.SocketException:Socket关闭)被抛出.我的最后一个方法是现在问你们.
我已经为测试目的创建了一个简单的服务器 - 客户端应用程序("真正的"应用程序使用相同的逻辑),见下文.
如果我重复调用相同的测试用例(例如通过TestNG的invocationcount注释参数或使用简单的for循环),在某些时候会有一个java.net.SocketException:Socket关闭.
下面的测试用例基本上只是启动服务器(打开服务器套接字),等待几毫秒然后再次关闭套接字.关闭服务器套接字涉及打开套接字,以便服务器从ServerSocket.accept()方法返回(请参阅Server#shutdown()).
我虽然可能是在ServerSocket.accept() - 行之后的代码的多线程问题.所以我用一个synchronized块暂时包围它 - 也没有帮助.
你知道为什么会抛出这个异常吗?
最好,克里斯
Server.java看起来像这样:
package multithreading;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;
public class Server {
private ServerSocket serverSocket;
private boolean isShuttingDown;
private final static Logger logger = Logger.getLogger(Server.class);
public void start() throws Exception {
try {
serverSocket = new ServerSocket(5000);
isShuttingDown = false;
} catch (Exception e) {
throw new RuntimeException("Starting up the server failed - aborting", e);
}
while (true) {
try {
Socket socket = serverSocket.accept();
if (!isShuttingDown) {
new Thread(new EchoRequestHandler(socket)).start();
} else {
logger.info("Server is going to shutdown");
break;
}
} catch (IOException e) {
logger.error("Error occured while waiting for new connections, stopping server", e);
throw e;
}
}
}
public synchronized boolean isRunning() {
if (serverSocket != null && serverSocket.isBound() && !serverSocket.isClosed() && !isShuttingDown) {
return true;
}
return false;
}
public synchronized void shutdown() throws IOException {
if (isRunning()) {
isShuttingDown = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
/*
* since the server socket is still waiting in it's accept()
* method, just closing the server socket would cause an
* exception to be thrown. By quickly opening a socket
* (connection) to the server socket and immediately closing
* it again, the server socket's accept method will return
* and since the isShuttingDown flag is then false, the
* socket will be closed.
*/
new Socket(serverSocket.getInetAddress(), serverSocket.getLocalPort()).close();
serverSocket.close();
} catch (IOException e) {
logger.error("Closing the server socket has failed - aborting now.", e);
throw e;
}
}
} else {
throw new IOException("Server socket is already closed which should not be the case.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试类执行以下操作:
package multithreading;
import java.io.IOException;
import org.testng.annotations.Test;
public class Testing {
// @Test(invocationCount=10, skipFailedInvocations=true)
@Test
public void loadTest() throws InterruptedException, IOException {
for (int i = 0; i < 10; i++) {
final Server s = new Server();
new Thread(new Runnable() {
@Override
public void run() {
try {
s.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(500);
gracefullyShutdownServer(s);
Thread.sleep(1000);
}
}
private void gracefullyShutdownServer(final Server server) throws InterruptedException {
try {
server.shutdown();
while (server.isRunning()) {
Thread.sleep(500);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪如下所示:
ERROR 2011-03-13 16:14:23,537 [Thread-6] multithreading.Server: Error occured while waiting for new connections, stopping server
java.net.SocketException: Socket closed
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:390)
at java.net.ServerSocket.implAccept(ServerSocket.java:453)
at java.net.ServerSocket.accept(ServerSocket.java:421)
at multithreading.Server.start(Server.java:26)
at multithreading.Testing$1.run(Testing.java:18)
at java.lang.Thread.run(Thread.java:680)
java.net.SocketException: Socket closed
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:390)
at java.net.ServerSocket.implAccept(ServerSocket.java:453)
at java.net.ServerSocket.accept(ServerSocket.java:421)
at multithreading.Server.start(Server.java:26)
at multithreading.Testing$1.run(Testing.java:18)
at java.lang.Thread.run(Thread.java:680)
Run Code Online (Sandbox Code Playgroud)
关于你应该如何处理收盘,JN是正确的.
至于为什么这不起作用,我认为竞争是你的服务器代码读取isShuttingDown没有同步.我不明白为什么值更改应该立即显示给服务器线程.所以很可能会进行另一轮比赛.
正如JN所说:接受服务器时处理异常.如果您想知道您的代码是否可能close在套接字上引发异常,请isShuttingDown确保您可以安全地访问它.(synchronized (this) {}块或者写一个非常短的同步访问器.)
在这个特定情况下,我认为制作isShuttingDown volatile就足够了,详见本developerWorks文章Java理论与实践:管理波动性.但要小心,这不是一个神奇的子弹.
| 归档时间: |
|
| 查看次数: |
7080 次 |
| 最近记录: |