0

Usecase:

1.Have a queue which is getting filled asynchronously from another source.

2.Need to consume the data from that queue one after another. There is a usecase(play a sound) for which data extraction from the queue should happen in every X sec when there are multiple elements in queue.

Below is a sample code snippet for that:

    Queue<Wrapper> q = new ConcurrentLinkedQueue<>();
    // filling up queue
    void add(A obj) {    
    synchronized (q) {
      q.add(obj);
      q.notify();
      }
     }

Below is the consumer code for extracting the data:

    class Consumer extends Thread {
    @Override
    public void run() {
        while ( true ) {
            try {
                synchronized ( q ) {
                    while ( q.isEmpty() )
                        q.wait();

                    // Get the  item off of the queue
                    A w = q.remove();
                    // Process the work item
                    playSomeSoundForXsec(w);
                    Thread.sleep(3000);
                }
            }
            catch ( InterruptedException ie ) {
                break; 
            }
        }
    }

}

Issues with the above code:

  1. Static code analysis error: "wait(..) should be used instead of "Thread.sleep(..)" when a lock is held

  2. When continuous events are getting filled to the queue, sound stops coming out.

what will be better way to handle the above usecase.

basu
  • 87
  • 1
  • 2
  • 10
  • I think static analysis error pretty much speaks for itsels. It's not quite clear what do you mean by "sound stops coming out". Do you mean it stops at all? Or lags (plays, then freezes, then plays again)? What is `playSomeSoundForXSec`? What is `X`? Is that method synchronously plays or just queues the file? – M. Prokhorov Jan 23 '18 at 14:17
  • What, all sound? Or just your app sound? Or just sound you play in `playSomeSound...`? – M. Prokhorov Jan 23 '18 at 14:45
  • My application notification sound stops coming from the device. playSomeSoundForXSec() is used to play a file which has a duration of eg. 3 sec, So i thought to put a delay of 3sec so that the sound can be clearly audible. If no delay is provided, sounds are playing on top of each other. That function creates an android Notification and sound is played by NotificationManager – basu Jan 23 '18 at 14:54
  • 1
    Maybe see [this other similar question](https://stackoverflow.com/questions/15809399/android-notification-sound). – M. Prokhorov Jan 23 '18 at 15:00

0 Answers0