DaTaBomB
DaTaBomB

Reputation: 633

Sharing an arraylist of bytearray between threads in java

I have one thread T1 producing some content (ArrayList<byte[]> type) and want a second thread T2 to read the most recent content produced by T1. How do I share this data between threads safely to ensure that T2 gets the latest content while ensuring T1 is not currently writing to the variable? I looked at the producer consumer model, but it doesnt seem like what I need since I only need to get the latest content.

Upvotes: 0

Views: 141

Answers (2)

Kayaman
Kayaman

Reputation: 73528

Your use case is described almost exactly in the sample code for java.util.concurrent.Exchanger.

Upvotes: 0

Vee20
Vee20

Reputation: 56

Update the content in a synchronized block or use the volatile keyword when declaring the variable. More info on volatile here http://tutorials.jenkov.com/java-concurrency/volatile.html

Upvotes: 1

Related Questions