Home  >  Article  >  Java  >  How to use hungry pattern in java singleton

How to use hungry pattern in java singleton

WBOY
WBOYforward
2023-05-20 20:04:041283browse

Instructions for use

1. Initialize the singleton when the class is loaded and return it directly when accessing in the future.

Advantages and Disadvantages

2. The advantage is that it is inherently thread-safe (thanks to the class loading mechanism) and there is no delay when using it. The disadvantage is that it may cause a waste of resources (if the singleton is not used after the class is loaded).

Example

public class HelloWorld {
//创建私有静态的本类对象
private static HelloWorld hello = new HelloWorld();
 
//私有化构造函数
private HelloWorld(){};
 
//定义公有并静态的方法,返回该对象。
public static HelloWorld hello() {  
return hello;
}
}

The above is the detailed content of How to use hungry pattern in java singleton. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete