Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SocketException: No buffer space available

My java code use several threads, each thread run a ServerSocket and goes in accept. These threads communicate each other using java socket. With 121 threads all work at well, but if I run same code with 256 thread I have this error:

java.net.SocketException: No buffer space available (maximum connections reached?): listen failed
    at java.net.PlainSocketImpl.socketListen(Native Method)
    at java.net.PlainSocketImpl.listen(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)

I use windows xp sp3, there are several post like this (here ), but nobody post a soution for this problem . I have also installed a windows patch for remove the limit on TCP connection but I not solved my problem.

like image 672
tulkas85 Avatar asked Dec 13 '22 12:12

tulkas85


2 Answers

The message says you may be running out of connections. Have you checked that? You can check the open sockets from the command line using:

netstat -n

Ensure that you are closing all sockets on both sides (in finally blocks). Remember that listening sockets remain open after you receive a connection. Don't open and close sockets too quickly (I'd say they can't be reused immediately which could be related to your issue).

For a better socket-related performance you can use the java.nio API, but it's far more complicated than java.net.

like image 185
jjmontes Avatar answered Dec 22 '22 00:12

jjmontes


This post I think might have your answer. Leaving dangling sockets would cause you to reach a maximum (which may be determined by some other setting that the windows patch does not fix (such as a JVM limit?)

As a side-note, if you're running with that many threads, it's highly likely that you would be better off using java.nio rather than java's simple Socket and ServerSocket classes.

This site is a very good tutorial for how to use java.nio and also how I learned it (along with looking at Sun/Oracle's Java NIO API), coming from using simple Socket and ServerSocket programming.

Specifically, what will help your cause is using a Selector, which will allow you to multiplex your socket I/O in the same manner that the C++ select() call works with sockets. This means that at the core of your socket code, you can reduce the impact of having a large number of threads dealing with socket I/O and only have one thread interacting directly with the sockets.

like image 25
devyndraen Avatar answered Dec 21 '22 22:12

devyndraen