java - Object pooling with .wait and .notify -
i'm trying create class in java pool objects. class starts creating minimum amount of objects required, when requests start kick in, every thread checks if there object available, if can create because maximum has not been reached yet, or if otherwise has wait one.
the idea threads needs synchronize get/create engine, can process in parallel (processwithengine method). processing take couple of minutes, , apparently it's working want.
the problem is, sometimes when .notify() has been called , thread released .wait(), queue has 0 items, , should impossible because before .notify(), item added.
what problem?
the code this:
queue _queue = new queue(); int _poolmax = 4; int _poolmin = 1; int _poolcurrent =0; public void process(object[] parameters) throws exception { engine engine = null; synchronized(_queue) { if(_queue.isempty() && _poolcurrent >= _poolmax) { _queue.wait(); // here : _queue.isempty() true @ point. engine = (spreadsheetengine)_queue.dequeue(); } else if (_queue.isempty() && _poolcurrent < _poolmax) { engine = createengine(); _poolcurrent++; } else { engine = (engine)_queue.dequeue(); } } processwithengine(engine, parameters); // work done synchronized(_queue) { _queue.enqueue(engine); _queue.notify(); } } i've fixed doing this:
{ _queue.wait(); } while(_queue.isempty()); but means thread losing turn, , mean timeout later on.
all calls .wait() have enclosed in while loop. calls wait() can randomly wake up.
per documentation: "as in 1 argument version, interrupts , spurious wakeups possible, , method should used in loop:"
Comments
Post a Comment