Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing a ThreadLocal variable in Java

In my small application I have threads of two classes - basically writers and readers. Multiple readers can be assigned to a single writer. A writer interacts with its readers by writing to their chunkBuffer variable.

Now, I can't quite wrap my head around the thread safety issue here: if I do not store the chunkBuffer in a static ThreadLocal variable, all readers will share a single chunkBuffer, which is bad. But if I do store the chunkBuffer in a static ThreadLocal, the writer, being a separate thread, will get its own copy of the chunkBuffer and will keep writing to it, while none of the data it writes will reach the readers. Can you explain to me what's the problem here? Thank you very much.

Edit In other words, is there a way to create a field that will be unique for every single instance of a thread subclass (like ThreadLocal), but can be accessed from other threads on demand?

like image 222
dpq Avatar asked Jun 10 '26 14:06

dpq


1 Answers

Nope.

ThreadLocal is for thread-private data. In your case you need objects to communicate so you need other type of objects.

I think the best structure to use is syncrhonized queues: java.util.concurrent.LinkedBlockingQueue<E>.

Queues allow a producer to insert data and a consumer to consume from. If it's sync it allow to do it from different threads without breaking the structure.

You can share a queue between the related writers/readers:

Writer 1 -> queue 1 -> [readers A/B/C]

Writer 2 -> queue 2 -> [readers D/E/F]

Each writer and reader will have its thread. Each reader will try to take one item from its queue blocking if there are no items. If you need to manage more wisely your readers you can try a more sophisticated approach but I think it's a good starting point.

like image 86
helios Avatar answered Jun 12 '26 10:06

helios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!