Sending objects back and forth between threads in java?

I have several threads of client handlers, these threads must pass the received object to the server queue, and the queue of queues will transfer another type of object back to the sending stream. The server queue is running and continues to run when the server starts. I'm not sure which thread mechanism to use for client handler threads is notified, the object is sent back. I am not going to use a socket or write to a file.

+5
source share
6 answers

If you want to do the actual messaging, see SynchronusQueue . Each thread will have a link to the queue and will wait until one thread passes the link through the queue.

It will be thread safe and will meet your requirements.

Although, if you just want the threads to read and write a shared variable, you can use the normalocity clause, although the safety of the threads depends on how you access it (through synchronized or unstable).

+5
source

, Java, . (, , ) . , , .

, , , . , , .

, , , , . , , , .

- LinkedList, , , , . , , , / .

+4

, , - .

, , - .: -)

+2

.

MyFirstThread extends Thread{
 public void setData(Object o){...}
}
MySecondThread extends Thread{
   MyFirstThread callback;
   MySecondThread(MyFirstThread callback){this.callback=callback)
}
MyFirstThread t1 = new MyFirstThread();
MySecondThread t2 = new MySecondThread(t1);    
t1.start();
t2.start();

callback.setData(...) .

, . volatile , , , .

BlockingQueue . , , , .

0
  • java.util.concurrent. *.

? , .

: , .

: : .

? .

: Request #getFutureResponse(). , , ( Atomic/CAS) ..

note: timeout Future SLA . #getFutureResponse (sla_timeout_ms).

0

Advisor for the book, if you want to dive a little into the connection between threads (or processes or systems): Architecture of pattern-oriented software Volume 2: Templates for parallel and network objects

0
source

All Articles