concurrency - Is this a good design for implementing the java synchronized keyword as an object? -
just practice wanted implement java synchronized keyword java object. code below design this? guess atomicreference have similar performance atomicboolean?
updated code after suggestions:
public class synchronizedblock implements runnable{ private final lock lock; private final runnable runnable; public synchronizedblock(runnable r, lock l){ runnable = r; lock = l; } public void run() { try { while(!lock.compareandset(false, true)){ thread.sleep(100); } runnable.run(); } catch (interruptedexception e) { e.printstacktrace(); } { lock.unlock(); } } } public class lock { private final atomicreference<boolean> locked = new atomicreference<boolean>(false); public boolean compareandset(boolean expected, boolean update){ return locked.compareandset(expected, update); } public boolean islocked(){ return locked.get(); } public void unlock(){ locked.set(false); } } @test public void test() { final synchronizedblock sb = new synchronizedblock(new runnable(){ public void run() { x++; system.out.println(x); } }, new lock()); runnable r1 = new runnable(){ int c = 0; public void run() { while(c<10){ sb.run(); c++; } } }; runnable r2 = new runnable(){ int c = 0; public void run() { while(c<10){ sb.run(); c++; } } }; thread t1 = new thread(r1); thread t2 = new thread(r2); t1.start(); t2.start(); while (t1.isalive() && t2.isalive()){ } assertequals(20,x); }
you should add method encapsulate compareandswap, , there no point looping lock free before attempting obtain it. why in situation can see lock free time try take it, gone.
i remove lock method , place unlock in lock exception/error doesn't result in lock never unlocks.
also use atomicboolean more natural atomicreference
Comments
Post a Comment