深入JVM之号称世界上所有Java程序员都会犯的一个错误

本文深入剖析了Java编程中常见的单例模式陷阱,通过具体实例展示了不同实现方式下单例对象的创建过程及可能产生的问题。重点讲解了两个单例类的实现步骤,包括静态变量的初始化、实例的创建与初始化,以及如何避免在面试中遇到此类问题。适合Java开发者学习参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

完整版见 https://jadyer.github.io/




package com.jadyer.classloader;

/**
 * 深入JVM之号称世界上所有Java程序员都会犯的一个错误
 * @author 宏宇
 * @editor Jan 24, 2012 7:49:18 PM
 * @see 这是一个很无耻的面试题,多么卑鄙的人才能写出这种自己给自己找麻烦的代码啊~~
 */
public class ClassLoadTest {
	public static void main(String[] args) {
		SingletonFront singletonFront = SingletonFront.getInstance();
		System.out.println("counter11 = " + singletonFront.counter11);
		System.out.println("counter22 = " + singletonFront.counter22);
		System.out.println("=============");
		SingletonBack singletonBack = SingletonBack.getInstance();
		System.out.println("counter33 = " + singletonBack.counter33);
		System.out.println("counter44 = " + singletonBack.counter44);
	}
}


/**
 * 单例类:在变量之前new的实例
 * @see Step01:为静态变量分配内存并初始化为默认值
 * @see 	   singletonFront=null,counter11=0,counter22=0
 * @see Step02:为静态变量赋正确的初始值,并初始化类的实例
 * @see		   singletonFront=new SingletonFront(),counter11=1,counter22先因为构造方法等于壹之后又因为初始值等于零
 */
class SingletonFront{
	private static SingletonFront singletonFront = new SingletonFront(); //注意这个位置
	public static int counter11;
	public static int counter22 = 0;
	private SingletonFront(){
		counter11++;
		counter22++;
	}
	public static SingletonFront getInstance(){
		return singletonFront;
	}
}


/**
 * 单例类:在变量之后new的实例
 * @see Step01:为静态变量分配内存并初始化为默认值
 * @see 	   counter11=0,counter22=0,singletonFront=null
 * @see Step02:为静态变量赋正确的初始值,并初始化类的实例
 * @see		   counter11与counter22都是先等于零之后又因为构造方法才等于壹,singletonFront=new SingletonFront()
 */
class SingletonBack{
	public static int counter33;
	public static int counter44 = 0;
	private static SingletonBack singletonBack = new SingletonBack(); //注意这个位置
	private SingletonBack(){
		counter33++;
		counter44++;
	}
	public static SingletonBack getInstance(){
		return singletonBack;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值