Wednesday 15 July 2015

java - Release lock of a map and grab lock of a value -


I have to put that object on a method that prints only those numbers that have not yet been received, So I've used the following code. The idea is that I use a map which stores the lock for every integer, a thread waits at the lock if it is already in the map, otherwise it will have a new lock as an integer Use Integer (A) as a lock for a integer a P> The problem is that I want to release the map lock and I wait on the lock Ahta extend which is obtained from the map, but a race condition occurs , is there any idea to solve the problem?

  public class sync_print {public static zero main (string [] args) {sync_print syobj = new sync_print (); Thread T1 = New thread (new worker (syobj, 10), "thread 1"); Thread T2 = New thread (new worker (syobj, 10), "thread 2"); Thread T3 = New thread (new worker (syobj, 4), "thread 3"); Thread T4 = New thread (new worker (syobj, 5), "thread 4"); Thread T5 = new thread (new worker (syobj, 5), "thread 5"); T1.start (); T2.start (); T3.start (); T4.start (); T5.start (); } Hashmap & lt; Integer, integer & gt; Lock_map = New Hashmap & lt; Integer, integer & gt; (); Zero print (int a) foot split option {synchronize (lock_map) {integer lock = lock_map.get (a); If (lock! = Null) {synchronize (lock) {System.out.println (Thread.currentThread (). GetName () + "Waiting"); Lock_map.notify (); Lock.wait (); }} And {lock_map.put (a, new integer (a)); Println (a); }}}} Class worker able to walk {int val; Sync_print obj; Public worker (sync_print obj, int v) {this.val = v; This.obj = obj; } Public run zero () {try {obj.print (val); } Grip (Obstructed E-Type E) {}}}    

You can change your Hashem with lock_map to lock_map.put to lock_map.putEfAssent .

No comments:

Post a Comment