Share data between two threads in java

2.1k views Asked by At

What I am looking for is the best solution for sharing data between two different threads. I already wrote my own solution, but I am very interested to listen to someone else's thoughts.

The scenario is the following: The main thread launches 2 different threads, which run together at the same time.

The first one (Reader) has to read values from an InputStream source and then store them into a java bean object.

The second one (Sender), every X seconds, has to get values from the previous java object and send them towards a web service.

The main particularity of the scenario is that the object have to be shared in "real-time". What I mean is:

The InputStream source who I mentioned above, has no end. The Reader thread read without stopping from this source and provides to update the instance of shared object with new values read. The Sender, every x second, has to take a "snapshot" of the object for sending it to a web service.

For this reason i believe that the Producer/Consumer pattern is not good to me, because the Producer thread is not able to produce a "complete" object, but he only can update continuously the same one.

Taking into account the fact that this program has to run in an embedded platform, performance and optimization are very important.

What is your solution?

-- EDIT -- Forgive me, i realized that an important feature (which make the others already answered stackoverflow questions not good for my purposes) of the scenario is missing, i have edited my question including also this last one part.

1

There are 1 answers

0
AudioBubble On

For this kind of producer/consumer pattern given high contention but little work done with the shared resource, it's generally better to burn CPU cycles with a spin-lock type CAS loop than a solution that involves thread suspension and context switches since the amount of work being done by the producer/consumer is so little that there's hardly any time spent accessing the shared resource (just a push/pop from a shared queue or read/write from an input stream in your case).

So you don't necessarily want to use Java synchronized methods here which could end up suspending threads repeatedly only to wake them up right after, making the repeated thread suspension and context switches into a bottleneck.

You want something using lower-level atomic CAS loops, like a concurrent queue (most concurrent queues are implemented this way, perhaps with thread suspension only if the number of attempts for an atomic CAS push/pop to succeed exceeds a certain number of cycles).