单例最佳实践——内部类

【Java踩坑笔记】23_double-checkedlocking单例,你写的真的线程安全吗? 双重检查锁(DCL)是实现懒加载单例的经典写法,但少了。 阅读详情

Java Singleton Design Pattern Best Practices with Examples

Java Singleton Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category. From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Java Singleton pattern has always been a controversial topic among developers. Here we will learn about Singleton design pattern principles, different ways to implement Singleton design pattern and some of the best practices for it’s usage.

Java Singleton

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
The singleton class must provide a global access point to get the instance of the class.
Singleton pattern is used for logging, drivers objects, caching and thread pool.
Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.
java singleton pattern, singleton class in java

Java Singleton Pattern

To implement Singleton pattern, we have different approaches but all of them have following common concepts.

Private constructor to restrict instantiation of the class from other classes.
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
In further sections, we will learn different approaches of Singleton pattern implementation and design concerns with the implementation.

Eager initialization
Static block initialization
Lazy Initialization
Thread Safe Singleton
Bill Pugh Singleton Implementation
Using Reflection to destroy Singleton Pattern
Enum Singleton
Serialization and Singleton

Eager initialization

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

Here is the implementation of static initialization singleton class.

package com.journaldev.singleton;

public class EagerInitializedSingleton {

private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}

public static EagerInitializedSingleton getInstance(){
    return instance;
}

}
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method. Also this method doesn’t provide any options for exception handling.

Static block initialization

Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.

package com.journaldev.singleton;

public class StaticBlockSingleton {

private static StaticBlockSingleton instance;

private StaticBlockSingleton(){}

//static block initialization for exception handling
static{
    try{
        instance = new StaticBlockSingleton();
    }catch(Exception e){
        throw new RuntimeException("Exception occured in creating singleton instance");
    }
}

public static StaticBlockSingleton getInstance(){
    return instance;
}

}
Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create Singleton class that supports lazy initialization.

Read: Java static

Lazy Initialization

Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.

package com.journaldev.singleton;

public class LazyInitializedSingleton {

private static LazyInitializedSingleton instance;

private LazyInitializedSingleton(){}

public static LazyInitializedSingleton getInstance(){
    if(instance == null){
        instance = new LazyInitializedSingleton();
    }
    return instance;
}

}
The above implementation works fine incase of single threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class. In next section, we will see different ways to create a thread-safe singleton class.

Thread Safe Singleton

The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.

package com.journaldev.singleton;

public class ThreadSafeSingleton {

private static ThreadSafeSingleton instance;

private ThreadSafeSingleton(){}

public static synchronized ThreadSafeSingleton getInstance(){
    if(instance == null){
        instance = new ThreadSafeSingleton();
    }
    return instance;
}

}
Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization). To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.

Below code snippet provides the double checked locking implementation.

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
Read: Thread Safe Singleton Class

Bill Pugh Singleton Implementation

Prior to Java 5, java memory model had a lot of issues and above approaches used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously. So Bill Pugh came up with a different approach to create the Singleton class using a inner static helper class. The Bill Pugh Singleton implementation goes like this;

package com.journaldev.singleton;

public class BillPughSingleton {

private BillPughSingleton(){}

private static class SingletonHelper{
    private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}

public static BillPughSingleton getInstance(){
    return SingletonHelper.INSTANCE;
}

}
Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.

This is the most widely used approach for Singleton class as it doesn’t require synchronization. I am using this approach in many of my projects and it’s easy to understand and implement also.

Read: Java Nested Classes

Using Reflection to destroy Singleton Pattern

Reflection can be used to destroy all the above singleton implementation approaches. Let’s see this with an example class.

package com.journaldev.singleton;

import java.lang.reflect.Constructor;

public class ReflectionSingletonTest {

public static void main(String[] args) {
    EagerInitializedSingleton instanceOne = EagerInitializedSingleton.getInstance();
    EagerInitializedSingleton instanceTwo = null;
    try {
        Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            //Below code will destroy the singleton pattern
            constructor.setAccessible(true);
            instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(instanceOne.hashCode());
    System.out.println(instanceTwo.hashCode());
}

}
When you run the above test class, you will notice that hashCode of both the instances are not same that destroys the singleton pattern. Reflection is very powerful and used in a lot of frameworks like Spring and Hibernate, do check out Java Reflection Tutorial.

Enum Singleton

To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.

package com.journaldev.singleton;

public enum EnumSingleton {

INSTANCE;

public static void doSomething(){
    //do something
}

}
Read: Java Enum

Serialization and Singleton

Sometimes in distributed systems, we need to implement Serializable interface in Singleton class so that we can store it’s state in file system and retrieve it at later point of time. Here is a small singleton class that implements Serializable interface also.

package com.journaldev.singleton;

import java.io.Serializable;

public class SerializedSingleton implements Serializable{

private static final long serialVersionUID = -7604766932017737115L;

private SerializedSingleton(){}

private static class SingletonHelper{
    private static final SerializedSingleton instance = new SerializedSingleton();
}

public static SerializedSingleton getInstance(){
    return SingletonHelper.instance;
}

}
The problem with above serialized singleton class is that whenever we deserialize it, it will create a new instance of the class. Let’s see it with a simple program.

package com.journaldev.singleton;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class SingletonSerializedTest {

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    SerializedSingleton instanceOne = SerializedSingleton.getInstance();
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
            "filename.ser"));
    out.writeObject(instanceOne);
    out.close();

    //deserailize from file to object
    ObjectInput in = new ObjectInputStream(new FileInputStream(
            "filename.ser"));
    SerializedSingleton instanceTwo = (SerializedSingleton) in.readObject();
    in.close();

    System.out.println("instanceOne hashCode="+instanceOne.hashCode());
    System.out.println("instanceTwo hashCode="+instanceTwo.hashCode());

}

}
Output of the above program is;

instanceOne hashCode=2011117821
instanceTwo hashCode=109647522
So it destroys the singleton pattern, to overcome this scenario all we need to do it provide the implementation of readResolve() method.

protected Object readResolve() {
return getInstance();
}

Java静态内部类实现单例过程 主要介绍了Java静态内部类实现单例过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 立即下载

相关推荐

Spacedesk保姆级教程:用旧平板给Windows电脑当副屏,从安装到避坑一步到位

本文提供Spacedesk保姆级教程,教你如何将旧平板变成Windows电脑的副屏,从软件安装到网络配置、显示优化及声音交互,一步步避开常见陷阱。通过WiFi实现扩展屏功能,支持4K分辨率和60Hz刷新率,让闲置设备焕发新生。

weixin_42524945的博客 1万+

单例模式的几种用法比较

最近在看何红辉、关爱民著的《Android源码设计模式解析与实战》,一边学习,一边理解,一边记笔记。 1.定义 确保某个类只有一个实例,能自行实例化并向整个系统提供这个实例。 2.应用场景 当产生多个对象会消耗过多资源,比如IO和数据操作 某种类型的对象只应该有且只有一个,比如Android中的Application。 3.考虑情况 多线程造成实例不唯一。 反序列化过...

旭日的芬芳 9135

VTK学习(入门级教程,包括安装和使用)~持续更新中

说明:研究QT+VTK有段时间了,准备把学到的东西分享给大家,这篇博客以VS+QT+VTK为主进行展开学习的。

HXX904的博客 4766

Java学习日记 | 内部类 | 单例模式

软件设计模式(Design pattern),又称设计模式,是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。前人栽树后人乘凉一般代表了最佳实践单例模式 : 让某个类只创建一个对象1 构造方法私有化,因为创建对象,使用构造方法,所以我们想要限制对象的创建,就要限制构造方法的使用2 创建一个用于保存对象的静态变量3 对外提供一个用于获取对象的方法(一定是静态方法)

m0_72373025的博客 526

基于DFT的mbist sdc模板(DFT)

摘要:本文详细介绍了DFT测试模式下的SDC约束方法。

murphyrong的博客 940

电脑卸载神器Revo Uninstaller Pro,彻底清残留,终身无限制使用

打开软件后,它会自动扫描并列出电脑里所有已安装的程序,小到各种插件、大到专业设计软件和驱动程序,哪怕是隐藏的系统组件,都能给你扒出来,还会自动分类整理,加上搜索功能能快速定位目标软件,就算是电脑小白,也能轻松上手。卸载彻底无残留:能直接代替系统自带的 “添加 / 删除程序”,不光能正常卸载软件,还会通过内置卸载程序配合残留扫描,把软件留下的残留文件、垃圾还有注册表项都扫得明明白白,扫描强度有三档可以选,想清理得多干净都能自己定,删除之后电脑立马清爽不少。电脑用久了是不是越来越慢?

qq_75153390的博客 1804

java 内部类 单例_内部类,单例模式

内部类:1.定义:在一个类中可以定义一个类,这个类就是内部类2.写法class Outer{class Inner{.........}}3.特点:①内部类不能和外部类重名②内部类的对象可以访问本类的属性和方法,也可以访问外部类的属性和方法(包括private声明的)4.内部类的分类:①成员内部类(1)定义:在类的内部,方法的外部所定义的类为成员内部类(2)特点:不能使用static变量(3)内...

weixin_36200490的博客 707

Upwork入门指南:如何创建吸引人的个人资料

本文详细介绍了如何在Upwork上创建并优化个人资料,帮助自由职业者吸引更多客户。内容包括: 注册与验证:从注册账号到邮箱验证的完整步骤。 个人资料填写:如何撰写吸引人的标题、简介,选择技能标签,以及设置专业头像和费率。 作品集与优化:上传高质量作品集,提升搜索排名和客户信任度。 常见问题解答:解决新手常见问题,如无工作经验或审核不通过。 通过本文的指导,你将学会打造一个专业且高效的个人资料,为在Upwork上获得更多机会奠定基础。

qq_61813593的博客 3551

单例模式--内部类

为什么静态内部类的单例模式是最推荐的?如何在反射的情况下保证单例?如何在反序列化中保证单例?针对上述三个问题有了这篇文章,以一种循序渐进的方式,引出最后一种单例设计模式,希望对大家能够有所帮助。单例设计模式1、饿汉式这种其实大家都懂,不多说,上代码。package singleton; public class Singleton1 { private static Singleton1 ...

zhmi_1015的专栏 539

全新YOLO26有效涨点改进专栏目录 | 本专栏持续更新500+篇内容 | 包含各种卷积、主干网络、各种注意力机制、检测头、损失函数、小目标检测改进、二次创新模块、独家创新等几百种创新点改进

🔥《2026年YOLO26改进专栏》🔥 🚀持续更新500+最前沿创新改进点(顶会顶刊论文/独家创新策略),涵盖主干网络、各种卷积、注意力机制、检测头等模块,助力科研论文发表与模型性能提升,支持检测/分割/分类任务。订阅即获完整可运行项目,提供专业QQ答疑群,适合科研发论文(SCI/CCF/核心)及工业应用(PCB/医学/遥感检测)。专栏价格将逐步上涨,早订更优惠! ⭐特色:非计算机专业友好、模块可自由组合、全网独家创新;📌适用:研究生大论文和小论文创新、小目标检测、多领域科研应用,满足不同研究需求。

Ai缝合怪、助力小伙伴高效发论文 5387

Electron - Electron failed to install correctly, please delete node_modules/electron and try install

Electron安装失败:Electron failed to install correctly, please delete node_modules/electron and try installing again,electron安装报错:Electron failed to install correctly...解决方案,Electron 未能正确安装,请删除 node_modules/electron,然后再次尝试安装,如何解决这个问题,手把手教你解决,在yarn dev时报错,electr

🏆 前端领域优质创作者 4381

深入理解单例模式:静态内部类单例原理

本文主要介绍java的单例模式,以及详细剖析静态内部类之所以能够实现单例的原理。首先我们要先了解下单例的四大原则:1.构造私有。2.以静态方法或者枚举返回实例。3.确保实例只有一个,尤其是多线程环境。4.确保反序列换时不会重新构建对象。我们常用的单例模式有:,我们来逐一分析下这些模式的区别。

zzp的博客 1134

深度解析:LPDDR5 Receiver 的挑战与应对

LPDDR5 的数据速率已经来到Tbit​DataRate1​≈156ps在6400Mbps时也就是说,。👉 这就是为什么成为 LPDDR5 的“标配”。

weixin_43199439的博客 217

JAVA几种单例模式实现

JAVA几种单例模式实现

xiaowangbadan0_0的博客 314

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Android中单例的写法

在Android开发中,单例模式是常用的设计模式之一,但由于Android的内存管理机制和多线程环境,实现不当容易导致内存泄漏或线程安全问题。

分享技术和日常 971

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

Java单例的正确使用姿势

Java单例模式可能是最简单也是最常用的设计模式,一个完美的单例需要做到哪些事呢? 单例(这不是废话吗) 延迟加载 线程安全 没有性能问题 防止序列化产生新对象 防止反射攻击 可以看到,真正要实现一个完美的单例是很复杂的,那么,让我这个司机带大家看一看正确姿势的单例。最佳实践单例之枚举 没错,直接就上最佳实践,就是这么任性这货长这样:public enum Singleton{ IN

Shuhui.Li 786

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

单例模式最佳实践及破环单例的几种可能方式及解决方案

这种方式,虽然返回的是我们创建过的单例对象,但是实际上会在内存中生成了一个对象,只是没有返回使用到而已,这种方式有导致内存分配开销增大的风险(实际上无所谓),就算不是单例,也会生成一个对象,而且还存在引用,这种都不会存在引用,更容易被垃圾回收机制释放内存。不同的类加载器,会重复加载一个类,目前没有办法阻止不同类加载器,重复创建一个类。但是不同的类加载器,有不同的命名空间,生成不同的class对象,表面上看,是生成了两个对象,但是这两个对象属于不同的class对象,且无法相互强转,不算是两个相同的实例。

韦建韩的博客 788

java 设计模式-单例

一、单例模式定义: 单例模式确保某个了某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在实际应用中,如打印机,线程池,日志等 二、单例模式特点:  1、单例类只能有一个实例。  2、单例类必须自己创建自己的唯一实例。  3、单例类必须给所有其他对象提供这一实例。 单例模式保证了全局对象的唯一性 实现单例模式的方法: 1 把构造函数设置为private 防止类被随意创建对...

weixin_30814319的博客 105

2. 单例模式怎么创建?(双重检查锁和静态内部类),如何防止反射破坏单例?

volatile作用:禁止CPU指令重排序 new对象底层三步:1分配堆内存 2初始化对象 3引用赋值 重排序可能导致3提前执行,其他线程拿到半初始化残缺对象,volatile杜绝该问题。枚举直接封死这条路。枚举序列化、反序列化由 JVM 特殊处理,永远返回同一个 INSTANCE 实例,不会产生新对象。作用:保证一个类在整个程序中,全局只有唯一一个实例对象,并且对外提过一个获取这个唯一实例的方法。普通单例实现,如果实现 Serializable 序列化接口,反序列化会生成全新对象,破坏单例。

yjyyc的博客 286

设计模式-单例

一、单例Singleton 1 饿汉式,类加载到内存后,就实例化一个单例,用JVM保证线程安全,不论是否用到都会初始化。 public class Singleton { private static final Singleton INSTANCE = new Singleton();//static 保证class被load到内存之后只加载一次,final保证此类不允许改变 private Singleton() {};//私有构造保证类不能被外部new出来 p...

232

校招准备系列:每天一道算法题(9)-单例

校招准备系列:每天一道算法题(9)-单例单例 是最为最常见的设计模式之一。对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计模式为单例。例如,对于 class Mouse (不是动物的mouse哦),我们应将其设计为 singleton 模式。你的任务是设计一个 getInstance 方法,对于给定的类,每次调用 getInstance 时,都可得到同一个实例。思考:首先,

技术心路 632

设计模式之单例Singleton

绝对详细、绝对清楚,中国人不骗中国人

cfa3288的博客 310

01-16-01 单例模式 - ServiceManager与LayoutInflater的单例实现

单例模式在Android源码中的应用总结 本文分析了Android源码中三种经典单例实现方式: ServiceManager - 饿汉式单例 全局唯一服务管理中心 使用静态变量缓存实例 线程安全通过静态初始化保证 LayoutInflater - DCL双重检查锁单例 每个Context关联独立实例 采用缓存机制避免重复创建 双重检查锁保证线程安全 InputMethodManager - 懒汉式单例 按Display ID区分实例 使用SparseArray缓存多实例 同步锁保证多线程安全 这些实现展示了

时代我西的博客 359

一个单例还能写出花来吗?

单例可以说是最简单的一个设计模式了,单例模式要求只能创建一个对象实例。通常的写法是声明私有的构造函数,提供静态方法获取单例的对象实例。 常见的单例写法就是饿汉式、懒汉式、双重加锁验证、静态内部类和枚举的方式,写法可能大家都知道,不过针对不同的写法还是有可以继续深挖一下的地方,让我们从最简单的几种写法开始回顾单例,不想看前面的话直接往后翻好了。 回顾几种实现方式 饿汉式 饿汉式的写法通常静态成员变量已经是初始化好的,优点是可以不加锁就获取到对象实例,线程安全,主要的缺点在于不是延加载,稍微存在内存的浪费,

az44yao的专栏 97

Java单例模式详解:实现方式与最佳实践

单例模式是创建型设计模式的核心代表,通过确保类只有一个实例并提供全局访问点,解决了资源共享和状态管理问题。其实现原理主要基于类加载机制和同步控制,在Java中可通过饿汉式、懒汉式、静态内部类等多种方式实现。从技术价值看,单例模式能有效减少资源消耗、提高访问效率,特别适用于配置管理、连接池等高频访问场景。在工程实践中,需要注意线程安全、反射防御等关键问题,其中枚举实现和静态内部类方案因其线程安全性和简洁性成为推荐选择。本文深入分析了各种实现方案的性能差异,并提供了框架集成、Android开发等典型应用场景的实

weixin_30765505的博客 402

Holder 方式的单例

一 点睛 Hold 方式的单例完全是借助了类加载的特点。 二 代码 package singleton.singleton3; // final 不允许继承 public final class Singleton { // 实例变量 private byte[] data = new byte[1024]; private static Singleton instance = null; private Singleton() { System

实践求真知 1071
上一篇: Apgache Common
下一篇: 最长公共子序列(Sequence not SubString)
sonny543
博客等级 码龄12年 23粉丝 24原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值