Search code examples
javamultithreadingjavaagents

Is there a way to communicate between two completely independent threads?


I am trying to communicate between two threads which do not share any object in Java (I am building a Java agent). What I need is something like the following :

Thread agentattachThread = ...;
otherThread.send("Hello");

And this would be handled like an interrupt in the Agent Attach thread, like so :

public void msgHandler(String msg) {
    ...
}

Thread.onMessageReceived(msgHandler);

EDIT - Considering the answers to my original post, my question becomes : does the JVM offer by default a synchronized object to which all threads could get a reference to ?


Solution

  • The only way to "communicate" from thread to thread without sharing some object is via Thread.interrupt() Obviously, the only signal you can send by this means is a true flag, and the receiver will only notice it when it uses certain methods, like Thread.interrupted(), or a method that raises InterruptedException.

    Because this is so limited, it's standard practice to share a thread-safe object between threads which offers the interface needed by the application. For example, you could give each thread a reference to the same BlockingQueue and send messages that way.

    Any public, static field is globally visible, so a shared object such as a queue could be accessed via such a field by any thread.

    The closest thing to that "built-in" to the JVM that comes to mind are system properties; essentially, this is a shared map via which any thread can set or get String-type entries. There might be some other facilities that could be abused in a similar way, but I can't imagine any reason to use something like this when a static field would serve.