msj121
msj121

Reputation: 2842

Wait until data is ready (Java)

I have a bluetooth socket that reads data.

I have three objects that are trying to get data. The bluetooth channel gets an integer that specifies which object should receive the data.

My issue:

How do I make each object "wait" until the data is available. So each object will be calling a "read" method on the bluetooth object. The bluetooth object will continue on its thread reading data, but should notify each object their data is ready (each one of those objects is blocking, waiting for it's input).

Should I use a wait/notify pattern, a while loop to wait until it is flagged that data is ready?

Thoughts? Thank you.

Upvotes: 0

Views: 1324

Answers (2)

Filip Malczak
Filip Malczak

Reputation: 3204

If I understood your issue properly, I'd use a queue.

I would set up following threads:

  • main thread that initializes all others
  • dispatcher thread that reads integer and data and pushes that data into the proper queue (choosing it by that integer)
  • several worker threads, one for each "destination" object, each reading from its own queue.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533740

A simple approach is to use a BlockingQueue for each object waiting. When you reading thread has a new object you can add it to the queue for that object.

// for the publisher
blockingQueue.offer(message);

// for the consumer
Object p = blockingQueue.take();

An alternative is to not use a thread for each actor or object but instead register a consumer.

// for the blue tooth reader
registerListener(key, consumer);

This way the thread reading the blue tooth also calls the code needed to perform the action for each "object"

Upvotes: 2

Related Questions