static code block execution times

1. The number of executions of static static code blocks in java classes  

1. In the init phase of class loading, all static blocks and fields are collected and executed in the class constructor of the class. The static block is executed only once, and the JVM guarantees that it is executed only once.

Second, code, use static code blocks in tool classes

public class FileTypeDetector {


	private static Properties mappings;
	
	public static Map<String, String> languageMap = new LinkedHashMap<String, String>();

	static {
		try {
			ClassPathResource prop = new ClassPathResource(
					"xxx.properties");
			mappings = PropertiesLoaderUtils.loadProperties(prop);
			Enumeration<Object> enu = mappings.elements();  
	        while (enu.hasMoreElements()) {  
	            String value = (String) enu.nextElement();  
	            languageMap.put(value, value);
	        }  
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}
}

3. The use of static code blocks 1. The project initializes some data, which can be processed in two places.    The first is to load a class when the project starts, and digitize the data (such as initializing basic data or database connection pool).    The second is to use a static static code block in a tool class. When the tool class is accessed for the first time, it will be initialized (only executed once) and saved to the static global property. When other classes access it again , the initialization data will be used directly (such as: connecting to the redis database and initializing the connection pool). 



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326698406&siteId=291194637