Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass sockets created to another Java Process

We have an application which creates many sockets which belongs to its thread, By design if this application somehow fails, all threads stop which is not wanted. So to overcome this issue, each thread must be separated from the main application, if one of the threads fails, the other ones should be running. One thing in our mind is to pass created socket to another java process, so what is the correct way?

An other approach also is welcome?

Waiting for your suggestions...

like image 508
whoi Avatar asked Feb 28 '23 22:02

whoi


2 Answers

Forking:

You can't pass a socket handle between Java processes using the normal API as far as I can tell. However, it does seem to be possible on windows using the Winsock 2 API. On Posix you should be able to fork a child process with access to the parent socket, since forked processes inherit the parent's sockets.

You could, I think, implement a new SocketImpl class which supports moving a socket handle to another process, but you'd need to write some JNI code to do it.

Sounds pretty hairy to me, I doubt forking a new process from within Java is a good idea!

Listeners:

Another approach might be to spawn a new 'listener' process which is essentially a new pre-forked worker. Each worker could then take turns to listen to the socket for connections. The workers would then need to coordinate with a control process which manages spawning new processes as needed.

I agree with @Bozho, if an error in one thread can take them all down (I guess it would have to be a JVM exception killing the whole app) you have a bigger problem. You should look at isolating the threads if possible.

like image 132
Kothar Avatar answered Mar 08 '23 07:03

Kothar


It isn't. (Sockets can't be serialized.)

When one thread fails, its exception should be caught, logged, and this should not interfere with other threads. So either design it to stop completely, or design it to not stop completely.

Or pass all the information about the socket (address/port) to another application, which itself could open a similar socket.

like image 44
Bozho Avatar answered Mar 08 '23 06:03

Bozho