Java

Topic: Design pattern

Explain the Single Thread Execution pattern in concurrency patterns?

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 have

Browse random answers: