This week, we are going to talk about a problem we may not notice in common concurrency code but may bite you later. Synchronize on Method Call Quick Question See the following code: thread one will start first, then thread two. So, will the first element of list printed? Or deeper, can second thread enter that synchronized block? List list; // thread one synchronized (list) { while ( true ) { try { Thread.sleep( 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } } } // thread two synchronized (list.get( 0 )) { System.out.println(list.get( 0 )); } Answer The answer is yes. Do you get it? let’s analyse what the essence of this problem. First, we can simply find the the lock of list is always hold by thread one for its infinite loop. So, whether the second thread can enter that synchronized block depends on whether we need to get the lock of list. Now, we need to understand: whether we get option one or option two wh...
Learn programming, still on the way