跳至主要内容

博文

目前显示的是标签为“multi-thread”的博文

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

Singleton and Synchronization

Why synchronized in singleton I will describe what I encounter to convince you it is really needed to do so. I have the Class A in the Thread-use : Singleton s1 = Singleton.getInstance(); synchronized(s1){ while (!B.ready){ s1.wait(); } // read from singleton } Then Class B in Thread-readData : // notice the volatile static volatile boolean ready = false; Singleton s2 = Singleton.getInstance(); synchronized(s2){ // read data than write to singleton ready = true; s2.notify(); } Then Singleton : public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } This getInstance() is not synchronized now. If the first thread enter the if clause first, then the second thread get the cpu also enter it ( if clause ) when the instance are still null , so they create two Singleton and return separately . As a result, the s1 and s2 point to the different objects which cause...