跳至主要内容

博文

目前显示的是标签为“concurrency”的博文

Synchronize on Method Call

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...

Concurrency: How to Wait

Basic wait When we want to coordinate multiple threads to run in order, there are many useful synchronizer classes in Java library for us to use, like Semaphore , CyclicBarrier , CountDownLatch etc. A common usage of synchronizer class is consumer and producer problem. If we decide to use some basic method from internal lock, we can do it like following: // thread one while (ready) { obj.wait(); } // thread two ready = true ; obj.notify(); // or, depends on situation, obj.notifyAll(); Or we can use explicit lock: Lock & Condition to do similar thing. condition .await () ; condition .signal () ; And the above code is more a practice than a real usage. If you really need to write a producer and consumer solution, BlockingQueue may be more convenient to do it. waitForAny When we get familiar with the common use of wait, we are going to implement waitForAny utility function based on other library code of java. Definition As what we always do, we...