hashmap - java Lock using MAP causing a deadlock -
i have written code 3 threads involved:- 1. thread1 -> decrements map created in main thread 2. thread2 -> responsible checking size of map, once 0, exit 3. thread3 -> starts work once size 0, waits till size 0.
thread1 easy implement, thread2 , thread3 using reentrantlock. problem is, thread2 not breaking once size of map reaches 0 , therefore thread3 blocked forever. not sure, problem. appreciated.
import java.util.hashmap; import java.util.map; import java.util.concurrent.locks.lock; import java.util.concurrent.locks.reentrantlock; public class mainclass { static map<string, string> map = new hashmap<string, string>(); public static void main(string[] args) { // todo auto-generated method stub map.put("key1", "valu1"); map.put("key2", "valu1"); map.put("key3", "valu1"); map.put("key4", "valu1"); map.put("key5", "valu1"); map.put("key6", "valu1"); lock lock = new reentrantlock(); decrementthread(lock); thread3(lock); thread2(lock); } static void decrementthread(lock lock) { system.out.println("starting decrement thread"); new thread(new runnable() { @override public void run() { try { integer = 0; while(i<6) { thread.sleep(2000); string key = "key" + ((++i).tostring()); system.out.println(key); map.remove(key); system.out.println("removed" + map.size()); } } catch(exception e) { e.printstacktrace(); } } }).start(); } static void thread3(final lock lock) { system.out.println("starting thread3"); new thread(new runnable() { @override public void run() { lock.lock(); system.out.println("got lock"); while(true) { //system.out.println(map.size()); if(map.size() == 0) { system.out.println("breaking"); break; } } system.out.println("unlocking"); lock.unlock(); } }).start(); } static void thread2(final lock lock) { system.out.println("starting mail thread"); new thread(new runnable() { @override public void run() { system.out.println("waiting lock"); lock.lock(); system.out.println("thread2 locked"); lock.unlock(); } }).start(); } }
thanks, amar
Comments
Post a Comment