This adds tasks to the executor as fast as it can.
Up vote 0 down vote favorite share g+ share fb share tw.
I am trying to write a part of a multithreaded program where each thread from a fixed thread pool tries to fetch an object from a Queue and if the Queue is empty the thread waits. The problem I am experiencing is that the memory used by the program keeps increasing. Public class Ex3 { public static LinkedBlockingQueue myLBQ = new LinkedBlockingQueue(10); public static void main(String argc) throws Exception { ExecutorService executor = Executors.
NewFixedThreadPool(3); myLBQ. Add(new Integer(1)); for (;;) { executor. Execute(new MyHandler(myLBQ)); } } } class MyHandler implements Runnable { LinkedBlockingQueue myLBQ; MyHandler(LinkedBlockingQueue myLBQ) { this.
MyLBQ = myLBQ; } public void run() { try { myLBQ.take(); } catch (InterruptedException e) { e.printStackTrace(); } } } I don't understand why the executor. Execute keeps firing when the threads should be waiting for an item to be added to the Queue. How do I modify my code to reflect this?
Java multithreading executorservice link|improve this question asked Jul 11 '11 at 15:07Mat1149.
This adds tasks to the executor as fast as it can. For (;;) { executor. Execute(new MyHandler(myLBQ)); } This will consume about 200 MB per second.
It doesn't have anything to do with whether there are tasks to perform or not. If you don't want to do this I suggest you move the loop to the runnable and add only one. This will cause it to wait for tasks forever.
A better approach is to use the ExecutorService's builtin queue to queue tasks. ExecutorService executor = Executors. NewFixedThreadPool(3); final int taskId = 1; executor.
Submit(new Runnable() { @Override public void run() { doSomething(taskId); } }); executor.shutdown(); This does the same thing, but is much simpler IMHO.
Thank you, I hadn't realised that items would be added to the queue regardless of whether or not threads are available to perform them. – Mat Jul 11 '11 at 15:38 You can change it so it rejects tasks and there is no waiting thread, but this typically results in a RejectedExecutionException which isn't what you want here either. – Peter Lawrey Jul 11 '11 at 15:50.
It's because you're creating a gazillion instances of MyHandler and inserting them in the internal queue of the executor. That infinite for loop is quite mean.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.