dpq
dpq

Reputation: 9268

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?

Upvotes: 3

Views: 3438

Answers (2)

user545680
user545680

Reputation:

I don't think you want to use a ThreadLocal variable. You really need a notification mechanism.

Writer does the following:

  1. Write to a reader's chunkBuffer
  2. Notify reader of new data.

There are lots of ways to do this in the java concurrency stuff, but what's usually the easiest and safest is to use an ArrayBlockingQueue. In your use case it sounds like each Reader will have its own ArrayBlockingQueue and it simply needs to read off the queue.

It of course will depend on your use case. Is it necessary to always work on the latest data or do you need to work on each write to chunkBuffer? These kinds of questions are necessary to work out which mechanism you need.

Note: Props to @helios for mentioning synchronous queues, hopefully my answer adds value.

Upvotes: 0

helios
helios

Reputation: 13841

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.

Upvotes: 2

Related Questions