Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending objects back and forth between threads in java?

I have multiple client handler threads, these threads need to pass received object to a server queue and the sever queue will pass another type of object back to the sending thread. The server queue is started and keeps running when the server starts.I am not sure which thread mechanism to use for the client handler threads notified an object is sent back. I don't intend to use socket or writing to a file.

like image 798
Kevin Q Avatar asked Dec 02 '11 16:12

Kevin Q


People also ask

How do you pass objects between threads?

You can use a BlockingQueue to pass an Object from one thread to another thread. You can also use Exchanger class for this purpose.

How do you pass data between threads in Java?

If you want synchronous communication between a main thread and a processing thread, you can use a SynchronousQueue. The idea is that the main thread passes data to the processing thread by calling put() , and the processing thread calls take() .

How do I share a variable between two threads?

You should use volatile keyword to keep the variable updated among all threads. Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem. Save this answer.

What is wait () and notify () in multiThreading?

The wait() method is defined in the Object class. The notify() method is defined in the Object class. 4. The wait() method is used for interthread communication. The notify() method is used to wake up a single thread.


1 Answers

If you wanted to do actual message passing take a look at SynchronusQueue. Each thread will have reference to the queue and would wait until one thread passed the reference through the queue.

This would be thread safe and address your requirements.

Though if you are simply looking to have threads read and write a shared variable you can use normalocity's suggestion though it's thread-safety depends on how you access it (via sychronized or volatile)

like image 140
John Vint Avatar answered Nov 02 '22 07:11

John Vint