Simple analysis of Java single-case mode

Source: Internet
Author: User

Single-case mode:There is only one instance during the runI. Key points:

1. A class has only one instance------the most basic -----(private constructors only)

2. The class must create the instance itself-----(defines a static private object of the Class)

3. The class must provide this instance to the entire system on its own---(Provides a static public method that returns a static private object that creates or acquires itself)

two. Basic single-case mode1. Lazy Mode

Lazy mode: When the class is loaded, no instances are created, and when the call is run, it is created ( in time for space )

Advantages and Disadvantages: Fast class loading, slow acquisition at run time, thread insecurity;

To solve the lazy mode thread safety method: (1) method body plus Synchronization (2) Double check lock

Lazy mode features:lazy Loading(lazy loading)

2. A Hungry man mode

A hungry man mode: initialization is done when the class is loaded. ( space Change Time )

Pros and Cons: Class loading is slow, but getting objects at run time is faster; thread safety

Three. Code display

Lazy Mode Code:

import java.io.IOException;

import Java.io.InputStream;

import java.util.Properties;

/**

* Tool class for reading database configuration files--Singleton mode

* */

Public class ConfigManager {

01 Defining static private objects of this class

Private Static ConfigManager ConfigManager;

Private Static Properties Properties;

02 Privatization This class constructs the method--Reads the configuration file

Private ConfigManager () {

Define the configuration file to read

String configfile = "Database.properties";

Properties = New Properties();

Get the configuration file as an input stream

/**

* ConfigManager.class.getClassLoader (): Get the root directory of this class

* getResourceAsStream (ConfigFile): Get the configuration file in the form of a stream

* */

InputStream is = ConfigManager. class. getClassLoader()

. getResourceAsStream(configfile);

Try {

Read the configuration file (put the stream into the properties object)

properties. Load(is);

} catch (ioexception e) {

E.printstacktrace();

} finally {

Try {

Close the stream

Is.close();

} catch (ioexception e) {

E.printstacktrace();

}

}

}

03 providing a global access interface

/**

* Lazy mode: Thread insecure, in the case of multithreading concurrency,

* Multiple ConfigManager instances may be created

*

*

* 001 Simple Lazy mode-for single thread security

* public static ConfigManager getinstance () {

if (ConfigManager = = null) {

ConfigManager = new ConfigManager ();

}

return ConfigManager;

}

* Troubleshooting Thread safety issues:

002. Method body plus synchronization, each time point only allows one thread to pass this method

public static synchronized ConfigManager getinstance () {

if (ConfigManager = = null) {

ConfigManager = new ConfigManager ();

}

return ConfigManager;

}

04 getting the value of the Properties object

Public String getstring (string key) {

return properties. GetProperty(key);

}

A Hungry man mode code

1 Importjava.io.IOException;2 ImportJava.io.InputStream;3 Importjava.util.Properties;4 5 /**6 * Tool class for reading database configuration files--Singleton mode7  * */8  Public classConfigManager {9     //01 defining static private objects of this classTenprivate static ConfigManager configmanager=new ConfigManager ();//Initialize Instance          Private StaticProperties Properties; the     //02 Privatization This class constructs the method--Reads the configuration file -     PrivateConfigManager () { -         //define the configuration file to read -String configfile = "Database.properties"; +Properties =NewProperties (); -         //get the configuration file as an input stream +         /** A * ConfigManager.class.getClassLoader (): Get the root directory of this class at * getResourceAsStream (configfile): Get the configuration file in the form of a stream -          * */ -InputStream is = ConfigManager.class. getClassLoader () - . getResourceAsStream (configfile); -         Try { -             //Read the configuration file (put the stream into the properties object) in Properties.load (IS); -}Catch(IOException e) { to e.printstacktrace (); +}finally { -             Try { the                 //Close the stream * is.close (); $}Catch(IOException e) {Panax Notoginseng e.printstacktrace (); -             } the         } +     } A     //03 providing a global access interface the      the /*a hungry man mode - * Thread Safety: Creates an instance when the class is loaded, because the instance is static, in * So only load once the  * */ the      About      Public StaticConfigManager getinstance () { the         returnConfigManager; the     } the  +  -     //04 Getting the value of the Properties object the      Publicstring getString (String key) {Bayi         returnProperties.getproperty (key); the     } the}

Note *********************

/**

* Single-instance mode explanation of various single-case pattern usage

*

* */

public class SingleTon {

A hungry man mode variants: Static code blocks

private static SingleTon SingleTon = null;

static {

Class loading is the execution of a static block of code that executes only once

SingleTon = new SingleTon ();

}

Private SingleTon () {}

public static SingleTon getinstance () {

return singleTon;

}

}

**************************************************

Double check lock for lazy mode thread safety

Private Static SingleTon SingleTon;

Private SingleTon () {

}

Public Static SingleTon getinstance() {

if (singleTon = = null) {//first check (the thread after the first concurrent thread will not pass here because it has been instantiated)

synchronized (SingleTon. class ) {//Lock, Class synchronization security (only one thread in a batch of concurrent threads is allowed to pass)

if (singleTon = = null) {//second re-check (non-null judgment, instance is empty, not empty)

SingleTon = new singleTon();//Verify all through, create instance

}

}

}

return SingleTon;

}

}

Test analog multi-threaded concurrency with double lock

Package cn.bdqn.util;

/**

* Threading Class

* Analog Multithreading concurrency

* */

Public class Threaddemo extends Thread {

Private String Threadno;

Public Threaddemo () {

}

Public Threaddemo (String threadno) {

this. Threadno = Threadno;

}

Public String getthreadno() {

return Threadno;

}

Public void Setthreadno (String threadno) {

this. Threadno = Threadno;

}

@Override

Public void Run () {

Super. Run();

Call simple Interest mode method, simulate test double lock

System. out. println(threadno);

SingleTon. getinstance (threadno);

}

}

Package cn.bdqn.util;

/*

* Test class, test thread double lock

*

* */

Public class ThreadTest {

Public Static void Main (String[] args) {

for (int i = 0; i < 7; i++) {//equivalent to the main thread, once the resource is fetched, an n child thread is generated instantaneously, equivalent to the concurrency

New Threaddemo("thread" + I). Start();//Create a sub-thread and turn on

if (i = = 3) {

Try {

Thread. Sleep ()// Simulate multiple batches of threads successively

System. out. println("sleep*********");

} catch (interruptedexception e) {

E.printstacktrace();

}

}

      }

Execution Result:

   *****************************************************

/**

* Static Inner class: Resolve a hungry man mode to implement lazy loading (lazy load)

*

* */

Create a static variable

Private Static SingleTon SingleTon;

Private construction

Private SingleTon (){}

Static Inner class

Private Static class Singletonhelp{

Create a static constant to complete the instantiation

Private Static Final SingleTon INSTANCE=new SingleTon();

}

Interfaces that provide global access

Public Static SingleTon getinstance() {

return Singletonhelp. INSTANCE;

}

Test method

Public Static void Test () {

System. out. println("test===============" +singleTon. toString());

}

Package cn.bdqn.util;

/**

* Test static internal classes

*

* */

Public class Test02 {

Public Static void Main (String[] args) {

System. out. println("singleton.getinstance () =======" +singleton. getinstance(). toString ());

The test () now reports a null pointer exception because no static class method is called, no instance is loaded, the lazy load effect is reached (that is, loading the instance when needed, loading the instance when the class is not loaded)

Singleton.test ();

}

}

*****************************************************

When to use simple interest mode: When comparing the performance of the system, such as I/O operation, read the configuration file

Lazy mode features:lazy Loading(lazy loading)

Lazy mode: Change space by Time

A hungry man mode: space change time (standard a Hungry man mode is common mode, there is no thread safety problem)

Simple analysis of Java single-case mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.