java - Releasing a lock as soon as it is passed -



java - Releasing a lock as soon as it is passed -

i have client-server architecture server has clients work in turns, passing parameter each time client supposed work. client work parameter, , when done, parameter becomes "invalid" , can no longer used work.

i'd avoid running garbage collector while going on, , i'm avoiding object allocations. plan server associate single parameter object each client, , pass same parameter every time client asked work. however, creates problem parameter have re-set "valid" while ensuring client (who may have kept reference parameter lastly time around) can't start using (say, in different thread) before asked begin doing work.

so of parameter's public methods synchronized, , "valid" state set, followed (synchronous) beginwork phone call client, within synchronized block. creates problem client unknowingly hold parameter's lock, cause problems if client wants split work multiple threads. introduced single-threaded executorservice server uses fork off phone call beginwork, ensures server release lock promptly. seems bad design me -- why should class need whole other thread?

so question is: given i've laid out, have made horrible design error has caused me overcomplicate class, or need complex?

interface client { public void dowork(param p); } interface param { public boolean isvalid(); } class server { private final executorservice executor = executors.newsinglethreadexecutor(); private final myparam[] params; private class myparam implements param { boolean isvalid; client client; runnable task = new runnable() { @override public void run() { client.dowork(myparam.this); } } @override public synchronized boolean isvalid() { homecoming isvalid; } } public void runclients() { while (true) { (myparam param : params) { synchronized(param) { param.isvalid = true; // fork client release lock promptly (ugly!) executor.execute(param.task); } // ... wait client finish ... } } } }

i fixed adding explicit reentrantlock param interface. instead of using synchronized block, lock param, , allow client unlock if wants to.

java design concurrency

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -