Is it a good idea to communicate between 2 threads using sockets in Java? What I am trying to achieve is Inter-process communication using socket programming/RPC mechanism.
closed as not a real question by gnat, Yusubov, Walter, Glenn Nelson, Kilian Foth Jan 31 at 13:19
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.
Your question is not clear. Do you intend to create a communication between two threads belonging to the same process?
If yes, it sounds like a bad idea. Sockets may be quite slower than memory sharing, because they use different mechanisms and it's simplier and faster to deal with memory locks than with sockets. Sockets will force you to use something initially designed for long-distance communications, where the communicating ententies have no solution to directly share their memory. A lot of mechanisms are used to take into account the network latency and reliability, the limitation of "pipes" buffers, etc. In an inter-thread communication, the situation is completely different and you can expect a significantly faster communication between the threads. In that case, what you are looking for is probably a producer-consumer model.
If you plan to create a real inter-process (or even inter-program) communication, a socket can be relevant. But then, no explicit notion of thread is needed. This is just a traditional socket messaging.
Use a BlockingQueue
The best way to communicate between threads running within the same JVM is to use a BlockingQueue. It's trivial to set up and makes the job simple. Typically a
You reach for sockets when you are dealing with processes that exist on other machines or are otherwise memory-isolated from you.