Java

Topic: Design pattern

Explain the Single thread execution pattern?

The Singleton pattern we discussed earlier contains two good examples of theSingle Thread Execution pattern. The problem motivating this pattern first arisesbecause this example uses lazy instantiation -- delaying instantiating until necessary-- thereby creating the possibility that two different threads may callgetInstance() at the same time:public static synchronized Sequence getInstance(){if(instance==null) // Lazy instantiation{instance = new Sequence();}return instance;}If this method were not protected against simultaneous access with synchronized,each thread might enter the method, test and find that the static instance referenceis null, and each might try to create a new instance. The last thread to finish wins,overwriting the first thread's reference. In this particular example, that might not beso bad -- it only creates an orphaned object that garbage collector will eventuallyclean up -- but had there been a shared resource that enforced single access, suchas opening a port or opening a log file for read/write access, the second thread'sattempt to create an instance would have failed because the first thread would havealready obtained exclusive access to the shared resource.Another critical section of code in the Singleton example is the getNext() method:public static synchronized int getNext(){return ++counter;}If this is not protected with synchronized, two threads calling it at the same timemight obtain the same current value and not the unique values this class is intendedto provide. If this were being used to obtain primary keys for a database insert, thesecond attempt to insert with same primary key would fail.As we discussed earlier, you should always consider the cost of using a pattern.Using synchronized works by locking the section of code when it is entered byone thread and blocking any other threads until the first thread is finished. If this iscode used frequently by many threads, this could cause a serious degradation inperformance.Another danger is that two threads could become deadlocked if one thread isblocked at one critical section waiting for the second, while the second thread isblocked at another critical section, waiting for the first.

Browse random answers: