i writing job queue using blockingqueue , executorservice. waiting new data in queue, if there data put queue, executorservice fetch data queue. problem using loop loops wait queue have data , cpu usage super high. new use api. not sure how improve this.
executorservice mexecutorservice = executors.newsinglethreadexecutor(); blockingqueue<t> mblockingqueue = new arrayblockingqueue(); public void handlerequests() { future<t> future = mexecutorservice.submit(new workerhandler(mblockingqueue, mqueuestate)); try { value = future.get(); } catch (interruptedexception | executionexception e) { e.printstacktrace(); } if (mlistener != null && returnedvalue != null) { mlistener.onnewitemdequeued(value); } } } private static class workerhandler<t> implements callable<t> { private final blockingqueue<t> mblockingqueue; private pollingqueuestate mqueuestate; pollingrequesthandler(blockingqueue<t> blockingqueue, pollingqueuestate state) { mblockingqueue = blockingqueue; mqueuestate = state; } @override public t call() throws exception { t value = null; while (true) { // problem here, loop takes full cpu usage if queue empty if (mblockingqueue.isempty()) { mqueuestate = pollingqueuestate.waiting; } else { mqueuestate = pollingqueuestate.fetching; } if (mqueuestate == pollingqueuestate.fetching) { try { value = mblockingqueue.take(); break; } catch (interruptedexception e) { log.e(tag, e.getmessage(), e); break; } } }
any suggestions on how improve appreciated!
you don't need test queue empty, take()
, thread blocks until data available.
when element put on queue thread awakens value set.
if don't need cancel task need:
@override public t call() throws exception { t value = mblockingqueue.take(); return value; }
if want able cancel task :
@override public t call() throws exception { t value = null; while (value==null) { try { value = mblockingqueue.poll(50l,timeunit.milliseconds); break; } catch (interruptedexception e) { log.e(tag, e.getmessage(), e); break; } } return value; }
Comments
Post a Comment