Motivation
Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns and involves only one class which is responsible to instantiate itself, ti make sure it creates only one instance and in the same time to provide a global point of access to that instance. In that case the instance can be used from everywhere without calling the directly the constructor each time.
Intent
Ensure that only one instance of a class is created.
Provide a global point of access to the object.
Implementation
The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.
The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is a class operation and is responsible for creating its own unique instance in case it is not created yet.
class Singleton{ private static Singleton m_instance; private Singleton() { ... } public static synchronized Singleton getInstance() { if (m_instance == null) m_instance = new Singleton(); return m_instance; } ... public void doSomething() { ... }}
In the code above it can be seen that the getInstance method ensure that only one instance of the class is created. The constructor should not be accessible from outside of the class to ensure that the only way of instantiating the class to be through the getInstance method.
The getInstance method is used also to provide a global point of access to the object and it can be used like this: Singleton.getInstance().doSomething();
Applicability & Examples
According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:
Example 1 - Logger Classes
The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.
Example 2 - Configuration Classes
The Singleton pattern is used to design the classes that provide the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoid reloading the values each time the configuration parameters are used.
Example 3 - Accesing resources in shared mode
It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classs in the application, working in an multithreading environment, that needs to operate actions on the serial port. In this case a singleton with synchronized methods has to be used to manage all the operations on the serial port.
Example 4 - Factories implemented as Singletons
Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstarct Factory or Factory Method and Singleton design patterns is a common practice.
Specific problems and implementation
Thread-safe implementation for multithreading use.
Lazy instantiation using double locking mechanism.
The standard implementation shown in the code above is a thread safe implementation, but it's not the best thread-safe implementation beacuse sinchronization is very expensive when we are talking about the performance. We can see that the syncronized method getInstance does not need to be checked for syncronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any syncronized block. This optimization consist in checking in an unsincronized block if the object is null and if not to check agoin and create it in an syncronized block. This is called double locking mechanism.
In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.
//Lazy instantiation using double locking mechanism.class Singleton{ private static Singleton m_instance; private Singleton() { System.out.println("Singleton(): Initializing Instance"); } public static Singleton getInstance() { if (m_instance == null) { synchronized(Singleton.class) { if (m_instance == null) { System.out.println("getInstance(): First time getInstance was invoked!"); m_instance = new Singleton(); } } } return m_instance; } public void doSomething() { System.out.println("doSomething(): Singleton does something!"); }}
A detialed discution(double locking mechanism) can be found on http://www-128.ibm.com/developerworks/java/library/j-dcl.html?loc=j
Early instantiation using implementation with static field
In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the m_instance member is declared static. This is why in this implementation we don't need to syncronize any portion of the code. The class is loaded once this guarantee the unicity of the object.
Singleton - A simple example (java) //Early instantiation using implementation with static field.class Singleton{ private static Singleton m_instance = new Singleton(); private Singleton() { System.out.println("Singleton(): Initializing Instance"); } public static Singleton getInstance() { return m_instance; } public void doSomething() { System.out.println("doSomething(): Singleton does something!"); }}
Protected constructor
It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This techique has 2 drawbacks and this is why singleton is not used as a base class:
First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().
Multiple singleton instances if classes loaded by different classloaders access a singleton.
If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.
Serialization
If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.
public class Singleton implements Serializable { ... // This method is called immediately after an object of this class is deserialized. // This method returns the singleton instance. protected Object readResolve() { return getInstance(); } }
Abstract Factory and Factory Methods implemented as singletons.
There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.
Hot Spot:
Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.
Monday, March 7, 2011
Wednesday, March 2, 2011
What is a Java Thread and How does it work?
What is a Java Thread and How does it work?
A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Programmer may use java thread mechanism to execute multiple tasks at the same time.
Thread class and run() Method
* Basic support for threads is in the java.lang.Thread class. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority.
* The run() method gives a thread something to do. Its code should implement the thread's running behavior.
There are two ways of creating a customized thread:
o Sub classing java.lang.Thread and Overriding run() method.
o Implementing the java.lang.Runnable Interface.
Thread Scheduling
* When we say that threads are running concurrently, in practice it may not be so. On a computer with single CPU, threads actually run one at a time giving an illusion of concurrency.
* The execution of multiple threads on a single CPU based on some algorithm is called thread scheduling.
* Thread scheduler maintains a pool of all the ready-to-run threads. Based on fixed priority algorithm, it allocates free CPU to one of these threads.
The Life Cycle of a Thread
The following diagram illustrates the various states that a Java thread can be in at any point during its life and which method calls cause a transition to another state.
Thread life cycle
* Ready-to-run
A thread starts its life cycle with a call to start(). For example
MyThread aThread = new MyThread();
aThread.start();
A call to start() will not immediately start thread's execution but rather will move it to pool of threads waiting for their turn to be picked for execution. The thread scheduler picks one of the ready-to-run threads based on thread priorities.
* Running
The thread code is being actively executed by the processor. It runs until it is swapped out, becomes blocked, or voluntarily give up its turn with this static method
Thread.yield();
Please note that yield() is a static method. Even if it is called on any thread object, it causes the currently executing thread to give up the CPU.
* Waiting
A call to java.lang.Object's wait() method causes the current thread object to wait. The thread remains in "Waiting" state until some another thread invokes notify() or the notifyAll() method of this object. The current thread must own this object's monitor for calling the wait().
* Sleeping
Java thread may be forced to sleep (suspended) for some predefined time.
Thread.sleep(milliseconds);
Thread.sleep(milliseconds, nanoseconds);
Please note that static method sleep() only guarantees that the thread will sleep for predefined time and be running some time after the predefined time has been elapsed.
For example, a call to sleep(60) will cause the currently executing thread to sleep for 60 milliseconds. This thread will be in ready-to-run state after that. It will be in "Running" state only when the scheduler will pick it for execution. Thus we can only say that the thread will run some time after 60 milliseconds.
* Blocked on I/O.
A java thread may enter this state while waiting for data from the IO device. The thread will move to Ready-to-Run after I/O condition changes (such as reading a byte of data).
* Blocked on Synchronization.
A java thread may enter this state while waiting for object lock. The thread will move to Ready-to-Run when a lock is acquired.
* Dead
A java thread may enter this state when it is finished working. It may also enter this state if the thread is terminated by an unrecoverable error condition.
Thread Synchronization
Problems may occur when two threads are trying to access/modify the same object. To prevent such problems, Java uses monitors and the synchronized keyword to control access to an object by a thread.
* Monitor
o Monitor is any class with synchronized code in it.
o Monitor controls its client threads using, wait() and notify() ( or notifyAll() ) methods.
o wait() and notify() methods must be called in synchronized code.
o Monitor asks client threads to wait if it is unavailable.
o Normally a call to wait() is placed in while loop. The condition of while loop generally tests the availability of monitor. After waiting, thread resumes execution from the point it left.
* Synchronized code and Locks
o Object lock
Each Object has a lock. This lock can be controlled by at most one thread at time. Lock controls the access to the synchronized code.
o When an executing thread encounters a synchronized statement, it goes in blocked state and waits until it acquires the object lock. After that, it executes the code block and then releases the lock. While the executing thread owns the lock, no other thread can acquire the lock. Thus the locks and synchronization mechanism ensures proper exceution of code in multiple threading.
Thread Priority
A thread's priority is specified with an integer from 1 (the lowest) to 10 (the highest), Constants Thread.MIN_PRIORITY and Thread.MAX_PRIORITY can also be used. By default, the setPriority() method sets the thread priority to 5, which is the Thread.NORM_PRIORITY.
Thread aThread = Thread.currentThread();
int currentPriority;
currentPriority = aThread.getPriority();
aThread.setPriority( currentPriority + 1 );
Setting priorities may not always have the desired effect because prioritization schemes may be implemented differently on different platforms. However, if you cannot resist messing with priorities, use higher priorities for threads that frequently block (sleeping or waiting for I/O). Use medium to low-priority for CPU-intensive threads to avoid hogging the processor down.
Thread Deadlock
In multiple threading, following problems may occur.
* Deadlock or deadly embrace occurs when two or more threads are trying to gain control of the same object, and each one has a lock on another resource that they need in order to proceed.
* For example, When thread A waiting for lock on Object P while holding the lock on Object Q and at the same time, thread B holding a lock on Object P and waiting for lock on Object Q, deadlock occurs.
* Please note that if the thread is holding a lock and went to a sleeping state, it does not loose the lock. However, when thread goes in blocked state, it normally releases the lock. This eliminates the potential of deadlocking threads.
* Java does not provide any mechanisms for detection or control of deadlock situations, so the programmer is responsible for avoiding them.
A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Programmer may use java thread mechanism to execute multiple tasks at the same time.
Thread class and run() Method
* Basic support for threads is in the java.lang.Thread class. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority.
* The run() method gives a thread something to do. Its code should implement the thread's running behavior.
There are two ways of creating a customized thread:
o Sub classing java.lang.Thread and Overriding run() method.
o Implementing the java.lang.Runnable Interface.
Thread Scheduling
* When we say that threads are running concurrently, in practice it may not be so. On a computer with single CPU, threads actually run one at a time giving an illusion of concurrency.
* The execution of multiple threads on a single CPU based on some algorithm is called thread scheduling.
* Thread scheduler maintains a pool of all the ready-to-run threads. Based on fixed priority algorithm, it allocates free CPU to one of these threads.
The Life Cycle of a Thread
The following diagram illustrates the various states that a Java thread can be in at any point during its life and which method calls cause a transition to another state.
Thread life cycle
* Ready-to-run
A thread starts its life cycle with a call to start(). For example
MyThread aThread = new MyThread();
aThread.start();
A call to start() will not immediately start thread's execution but rather will move it to pool of threads waiting for their turn to be picked for execution. The thread scheduler picks one of the ready-to-run threads based on thread priorities.
* Running
The thread code is being actively executed by the processor. It runs until it is swapped out, becomes blocked, or voluntarily give up its turn with this static method
Thread.yield();
Please note that yield() is a static method. Even if it is called on any thread object, it causes the currently executing thread to give up the CPU.
* Waiting
A call to java.lang.Object's wait() method causes the current thread object to wait. The thread remains in "Waiting" state until some another thread invokes notify() or the notifyAll() method of this object. The current thread must own this object's monitor for calling the wait().
* Sleeping
Java thread may be forced to sleep (suspended) for some predefined time.
Thread.sleep(milliseconds);
Thread.sleep(milliseconds, nanoseconds);
Please note that static method sleep() only guarantees that the thread will sleep for predefined time and be running some time after the predefined time has been elapsed.
For example, a call to sleep(60) will cause the currently executing thread to sleep for 60 milliseconds. This thread will be in ready-to-run state after that. It will be in "Running" state only when the scheduler will pick it for execution. Thus we can only say that the thread will run some time after 60 milliseconds.
* Blocked on I/O.
A java thread may enter this state while waiting for data from the IO device. The thread will move to Ready-to-Run after I/O condition changes (such as reading a byte of data).
* Blocked on Synchronization.
A java thread may enter this state while waiting for object lock. The thread will move to Ready-to-Run when a lock is acquired.
* Dead
A java thread may enter this state when it is finished working. It may also enter this state if the thread is terminated by an unrecoverable error condition.
Thread Synchronization
Problems may occur when two threads are trying to access/modify the same object. To prevent such problems, Java uses monitors and the synchronized keyword to control access to an object by a thread.
* Monitor
o Monitor is any class with synchronized code in it.
o Monitor controls its client threads using, wait() and notify() ( or notifyAll() ) methods.
o wait() and notify() methods must be called in synchronized code.
o Monitor asks client threads to wait if it is unavailable.
o Normally a call to wait() is placed in while loop. The condition of while loop generally tests the availability of monitor. After waiting, thread resumes execution from the point it left.
* Synchronized code and Locks
o Object lock
Each Object has a lock. This lock can be controlled by at most one thread at time. Lock controls the access to the synchronized code.
o When an executing thread encounters a synchronized statement, it goes in blocked state and waits until it acquires the object lock. After that, it executes the code block and then releases the lock. While the executing thread owns the lock, no other thread can acquire the lock. Thus the locks and synchronization mechanism ensures proper exceution of code in multiple threading.
Thread Priority
A thread's priority is specified with an integer from 1 (the lowest) to 10 (the highest), Constants Thread.MIN_PRIORITY and Thread.MAX_PRIORITY can also be used. By default, the setPriority() method sets the thread priority to 5, which is the Thread.NORM_PRIORITY.
Thread aThread = Thread.currentThread();
int currentPriority;
currentPriority = aThread.getPriority();
aThread.setPriority( currentPriority + 1 );
Setting priorities may not always have the desired effect because prioritization schemes may be implemented differently on different platforms. However, if you cannot resist messing with priorities, use higher priorities for threads that frequently block (sleeping or waiting for I/O). Use medium to low-priority for CPU-intensive threads to avoid hogging the processor down.
Thread Deadlock
In multiple threading, following problems may occur.
* Deadlock or deadly embrace occurs when two or more threads are trying to gain control of the same object, and each one has a lock on another resource that they need in order to proceed.
* For example, When thread A waiting for lock on Object P while holding the lock on Object Q and at the same time, thread B holding a lock on Object P and waiting for lock on Object Q, deadlock occurs.
* Please note that if the thread is holding a lock and went to a sleeping state, it does not loose the lock. However, when thread goes in blocked state, it normally releases the lock. This eliminates the potential of deadlocking threads.
* Java does not provide any mechanisms for detection or control of deadlock situations, so the programmer is responsible for avoiding them.
Subscribe to:
Posts (Atom)