在等待连接期间,线程究竟挂在 ServerSocket.accept() 的什么位置?
Where exactly does a thread hang in a ServerSocket.accept() during waiting for a connection?
在下面的块中,我了解到这个主线程正在阻塞,因此没有监听来自其他线程的中断,但这是否意味着它真的挂在 ServerSocket.accept() 行上?
ServerSocket serverSocket = new ServerSocket(8080);
while(true){ // Block until accept
Socket acceptedSocket = serverSocket.accept(); // Give accepted socket OR NULL SOCKET to acceptedSocket
handle(acceptedSocket);
serverSocket.close();
}
我问是因为我不明白它会在哪里挂断接受 (ServerSocket.java):
public Socket accept() throws IOException {
if (isClosed()) // No its open
throw new SocketException("Socket is closed");
if (!isBound()) // No its bound to 8080
throw new SocketException("Socket is not bound yet");
Socket s = new Socket((SocketImpl) null); // Create a null socket
implAccept(s); // Here???
return s;
}
ServerSocket.java 再一次:
protected final void implAccept(Socket s) throws IOException {
SocketImpl si = null;
try {
if (s.impl == null)
s.setImpl();
else {
s.impl.reset();
}
si = s.impl;
s.impl = null;
si.address = new InetAddress();
si.fd = new FileDescriptor();
getImpl().accept(si); // I'm thinking its here but when I look at this accept, thats an abstract method and don't know where to dig deeper.
取决于OS,但在Linux,accept()是内核调用。最直接的 Java 实现是使用该内核调用。
所以过程是'waiting in the kernel',粗略地说。
在下面的块中,我了解到这个主线程正在阻塞,因此没有监听来自其他线程的中断,但这是否意味着它真的挂在 ServerSocket.accept() 行上?
ServerSocket serverSocket = new ServerSocket(8080);
while(true){ // Block until accept
Socket acceptedSocket = serverSocket.accept(); // Give accepted socket OR NULL SOCKET to acceptedSocket
handle(acceptedSocket);
serverSocket.close();
}
我问是因为我不明白它会在哪里挂断接受 (ServerSocket.java):
public Socket accept() throws IOException {
if (isClosed()) // No its open
throw new SocketException("Socket is closed");
if (!isBound()) // No its bound to 8080
throw new SocketException("Socket is not bound yet");
Socket s = new Socket((SocketImpl) null); // Create a null socket
implAccept(s); // Here???
return s;
}
ServerSocket.java 再一次:
protected final void implAccept(Socket s) throws IOException {
SocketImpl si = null;
try {
if (s.impl == null)
s.setImpl();
else {
s.impl.reset();
}
si = s.impl;
s.impl = null;
si.address = new InetAddress();
si.fd = new FileDescriptor();
getImpl().accept(si); // I'm thinking its here but when I look at this accept, thats an abstract method and don't know where to dig deeper.
取决于OS,但在Linux,accept()是内核调用。最直接的 Java 实现是使用该内核调用。
所以过程是'waiting in the kernel',粗略地说。