concurrency - Active Object Pattern in Concurrent Java 1.5+ -
i trying develop active object pattern in concurrent java using java.util.concurrent
classes.
i describe using client
, server
. sample server
as:
class server implements runnable { public final linkedblockingqueue que = new linkedblockingqueue(); private final executorservice es = executors.newcachedthreadpool(); private message currentmessage; private boolean state = false; public init() { es.submit(this); } public void requestforserver() { if (state) { this.currentmessage.await(); } state = true; } public void run() { for(;;) { message m = que.take(); this.currentmessage = m; this.es.submit(m); } } }
and sample client
:
class client { private server server; public client(server s) { this.server = s; } public void dosomething() { message m = new message(new callable() { public object call() { server.requestforserver(); } }); this.server.que.add(m); } }
and sample message
encapsulation is:
class message<v> extends futuretask<v> { private lock lock = new reentrantlock(); private condition condition = new condition(); public message(callable<v> callable) { super(callable); } public void run() { try { lock.lock(); super.run(); lock.unlock(); } catch(exception e) {} } public void await() { try { condition.await(); } catch(exception e) {} } public void signal() { try { condition.signalall(); } catch(exception e) {} } }
and sample running code:
server s = new server(); client c = new client (s); s.init(); c.dosomething();
i dropped implementation details message across.
now, problem when in server
state
true
incoming message should wait , await
called on current message. however, illegalmonitorstateexception
means current message not own current thread await on it. but, believe strange since current message gets called in server
, thread pool current message has access current thread of execution.
i'd thankful ideas or suggestions, or known working implementation of pattern using java.util.concurrent
. in advance.
update:
discussed solution deploy in blog post. hope help.
you have acquire lock when await on corresponding condition. without lock cannot associate condition directly. demonstrate this:
public void await() { lock.lock(); try { condition.await(); } catch(exception e) {} finally{ lock.unlock(); } }
that should resolve illegalmonitorstateexception
on side note of correctness should release lock in try{ } finally{ } manner, can observe wrote example. reason if exception occurs between lock().lock();
, super.run();
lock.unlock()
never called.
Comments
Post a Comment