Java synchronized vs deadlock example -
i not familiar threads , concurrent programming. looking simple snippet result in deadlock, here :
public class testlock { private static class fun { int a,b; void read() {system.out.println(a+b);} void write(int a,int b) {this.a=a;this.b=b;} } public static void main (string[] args) throws java.lang.exception { final fun d1=new fun(); final fun d2=new fun(); thread t1=new thread() { public void run() { for(int i=0;i<5;i++) { synchronized(d2) { d2.read(); try { thread.sleep(50); } catch (exception ex) { ex.printstacktrace(); } synchronized(d1) { d1.write(i, i); } } } }; thread t2=new thread() { public void run() { for(int i=0;i<5;i++) { synchronized(d1) { d1.read(); try { thread.sleep(50); } catch (exception ex) { ex.printstacktrace(); } synchronized(d2) { d2.write(i, i); } } } } }; t1.start(); t2.start(); } }
now wondering how transform example, using reentrantlock instead of synchronized, don't see how : fun need have reentrantlock attribute in order have like
thread t1=new thread() { public void run() { for(int i=0;i<5;i++) { if(d2.lock.trylock()) { try {d1.read();thread.sleep(50);} catch(exception e) {e.printstacktrace();} {d1.lock.unlock();} if(d2.lock.trylock()) { try {d2.write(i, i);} catch(exception e) {e.printstacktrace();} {d2.lock.unlock();} } } } } };
or missing entirely ?
transforming example using reentrantlocks indeed mean using 2 locks: 1 associated d1
, other 1 associated d2
.
and replace every entrance in synchronized block on dx
call lockx.lock()
, , exit synchronized block on dx
call lockx.unlock()`.
using trylock()
defeats purpose, since returns instead of waiting if lock can't acquired.
Comments
Post a Comment