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?

2
  • 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 : javarevisited.blogspot.in/2012/02/… Commented Jul 8, 2015 at 7:52
  • The queue is shared between producer and consumer. Commented Jul 8, 2015 at 8:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.