multithreading - Doesn't executor service in java submits tasks parallelly? -
i playing java multithreading code. created executor service fixed thread pool. submitting 2 tasks sequentially. tried make first task long thread.sleep. thinking these 2 tasks run parallelly. however, when run program, programs waits sometime, prints b, means compiler finished first task @ first before going second task. actually, expecting, second task short task, complete before first task. explanation please?
public static void main(string[] args) { executorservice executor = executors.newfixedthreadpool(10); map<string, string> map = new hashmap<>(); readwritelock lock = new reentrantreadwritelock(); executor.submit(() -> { lock.writelock().lock(); try { thread.sleep(10000); map.put("boo", "mar"); system.out.println("a"); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } { lock.writelock().unlock(); } }); executor.submit(() -> { lock.writelock().lock(); try { thread.sleep(1); map.put("foo", "bar"); system.out.println("b"); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } { lock.writelock().unlock(); } }); executor.shutdown(); }
you "locking" writelock
before first thread sleeps.. lock locked 10 seconds.. unlocked. second thread waiting 10 seconds acquire lock.
sequence of events:
thread 1: starts thread 2: starts thread 1: acquire lock , wait 10 seconds. thread 2: try acquire lock (ends waiting 10 seconds because acquired thread 1). thread 1: prints data. thread 1: unlocks lock. thread 2: acquires lock. thread 2: prints data. thread 2: unlocks lock.
try below (it acquires lock when necessary.. ie: when doing write operation or modification of map):
public static void main(string[] args) { executorservice executor = executors.newfixedthreadpool(10); map<string, string> map = new hashmap<>(); readwritelock lock = new reentrantreadwritelock(); executor.submit(() -> { try { thread.sleep(10000); lock.writelock().lock(); map.put("boo", "mar"); lock.writelock().unlock(); system.out.println("a"); } catch (interruptedexception e) { e.printstacktrace(); } }); executor.submit(() -> { try { thread.sleep(1); lock.writelock().lock(); map.put("foo", "bar"); lock.writelock().unlock(); system.out.println("b"); } catch (interruptedexception e) { e.printstacktrace(); } }); executor.shutdown(); }
Comments
Post a Comment