0

I wrote a Class 'Producer' which is continuously parsing files from a specific folder. The parsed result will be stored in queue for the Consumer.

public class Producer extends Thread
{ 
    private BlockingQueue<MyObject> queue;
    ...
    public void run()
    {
        while (true)
        {
        //Store email attachments into directory
        ...
        //Fill the queue
        queue.put(myObject);


        sleep(5*60*1000);
        }
    }
}

My Consumer Class is continuously checking if there is something available in the queue. If so, it's performing some work on the parsed result.

public class Consumer extends Thread
{ 
    private BlockingQueue<MyObject> queue;
    ...
    public void run()
    {
        while (true)
        {
        MyObject o = queue.poll();

        // Work on MyObject 'o'
        ...
        sleep(5*60*1000);
        }
    }
}

When I run my programm, 'top' shows that the JAVA process is always on 100%. I guess it's because of the infinite loops.

Is this a good way to implement this or is there a more resource saving way for doing this?

mr.proton
  • 993
  • 2
  • 10
  • 24
  • 2
    Are you not using shared queue in both producer and consumer? CPU usage is zero in my case if I am using shared queue.Just have a look at this link : http://javarevisited.blogspot.in/2012/02/producer-consumer-design-pattern-with.html – Ravindra babu Jul 08 '15 at 07:52
  • The queue is shared between producer and consumer. – mr.proton Jul 08 '15 at 08:11

1 Answers1

4

Instead of

MyObject o = queue.poll();

try

MyObject o = queue.take();

The latter will block until there is something available in the queue, whereas the former will always return immediately, whether or not something is available.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243