Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

closed as not a real question by gnat, Yusubov, Walter, Glenn Nelson, Kilian Foth Jan 31 '13 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.

7  
"threads" are not processes. So communicating between to threads (in the same process) is not "inter-process communication". What do you want to achieve: share some information between threads or learn about inter-process communication? You can use threads to communicate between threads, but it's a lot more complicated than the alternative. –  Joachim Sauer Jan 31 '13 at 7:29
add comment

2 Answers

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 LinkedBlockingQueue is the first one to choose for general purpose requirements.

You reach for sockets when you are dealing with processes that exist on other machines or are otherwise memory-isolated from you.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.