Singleton
1) Eager Loading
Good for small class definitions:
package com.gs.ilp.innerclasses;
/**
*
* Singleton
*
* @author mohitmalhotra
*
*/
public class StudentUpdateDAOImpl {
private static StudentUpdateDAOImpl _instance = new StudentUpdateDAOImpl();
public static StudentUpdateDAOImpl getInstance() {
return _instance;
}
private StudentUpdateDAOImpl() {
}
// instance variable
public void saveStudent() {
// making save DB
}
public int getTotalStudentCount() {
return 12;
}
}
2) Lazy Loading
package com.gs.ilp.innerclasses;
/**
*
* Singleton
*
* @author mohitmalhotra
*
*/
public class StudentUpdateDAOImpl {
private static StudentUpdateDAOImpl _instance;
public static StudentUpdateDAOImpl getInstance() {
if (null == _instance) {
_instance = new StudentUpdateDAOImpl();
}
return _instance;
}
private StudentUpdateDAOImpl() {
}
// instance variable
public void saveStudent() {
// making save DB
}
public int getTotalStudentCount() {
return 12;
}
}
Issue: Thread safety
package com.gs.ilp.innerclasses;
/**
*
* Singleton
*
* @author mohitmalhotra
*
*/
public class StudentUpdateDAOImpl {
private static StudentUpdateDAOImpl _instance;
public static StudentUpdateDAOImpl getInstance() {
if (null == _instance) {
_instance = new StudentUpdateDAOImpl();
}
return _instance;
}
private StudentUpdateDAOImpl() {
}
// instance variable
public void saveStudent() {
// making save DB
}
public int getTotalStudentCount() {
return 12;
}
}
com.gs.ilp.innerclasses.StudentUpdateDAOImpl@16f1d982
com.gs.ilp.innerclasses.StudentUpdateDAOImpl@3941366b
3) Thread safe - Lazy Loading
package com.gs.ilp.innerclasses;
/**
*
* Singleton
*
* @author mohitmalhotra
*
*/
public class StudentUpdateDAOImpl {
private static StudentUpdateDAOImpl _instance;
public static StudentUpdateDAOImpl getInstance() {
synchronized (StudentUpdateDAOImpl.class) {
if (null == _instance) {
_instance = new StudentUpdateDAOImpl();
}
}
return _instance;
}
private StudentUpdateDAOImpl() {
}
// instance variable
public void saveStudent() {
// making save DB
}
public int getTotalStudentCount() {
return 12;
}
}
4) Thread safe - Lazy Loading - Starvation : performance issue
Double check locking :
package com.gs.ilp.innerclasses;
/**
*
* Singleton
*
* @author mohitmalhotra
*
*/
public class StudentUpdateDAOImpl {
private static volatile StudentUpdateDAOImpl _instance;
public static StudentUpdateDAOImpl getInstance() {
if (_instance == null) {
synchronized (StudentUpdateDAOImpl.class) {
if (null == _instance) {
_instance = new StudentUpdateDAOImpl();
}
}
}
return _instance;
}
private StudentUpdateDAOImpl() {
}
// instance variable
public void saveStudent() {
// making save DB
}
public int getTotalStudentCount() {
return 12;
}
}
Last updated