Design Mode: Metadata mode and Design Mode

Source: Internet
Author: User

Design Mode: Metadata mode and Design Mode
Meta Mode

Flyweight stands for lightweight. When I first came into contact with this term, I felt like a share model (sharing element), hahaha. The metadata mode is an implementation of the Object pool. What is an object pool? Do you understand the thread pool? The thread pool contains all threads, so the object pool should be all objects. The metadata-sharing mode is designed to avoid excessive memory waste and is suitable for creating a large number of duplicate objects. You can use cached objects to share objects, avoid creating too many objects. In this way, the program performance can be improved, and memory removal can be avoided.

I think every mobile development knows the image request framework, such as gilde, Picasso, Fresco, and other excellent open-source projects, then you must know that these request frameworks must use the cache component to cache the images already loaded when requesting images, so that you can directly use the cache when loading images of the same url next time. In this way, the metadata mode is like the cache component in the request framework. Some objects are created according to certain conditions at the beginning, and then, when necessary, you can obtain the corresponding object directly in the object pool (the container implementing the object pool in Java is generally Map.

Simple instance

Every one of us has used the Netease news app. Every soul of Ben San knows that it has a glorious title of "Huang Yi". Of course, today we will not talk about Huang Yi, let's take a look at Huang Yi's method of obtaining the Yuan-sharing model contained in NetEase news. Of course, the example is a little simpler. We don't consider distributing different personal content. We only consider that every day (time) Netease will give different news, news is the same for everyone. The specific scenario is that million people refresh Netease news every day. If no cache is used, then Netease's server will query million SQL queries for million people respectively, get identical results, then Netease's server crashes, and then we start to play toutiao, haha. Let's use the program to explain the corresponding process.

First, we define an interface to display news information:

Public interface News {/*** display News content */void showInfo ();}

Defines an implementation class for daily news. Here, it is simple to show news information only in time:

Public class EveryDayNews implements News {private String time; public EveryDayNews (String time) {this. time = time ;}@ Override public void showInfo () {System. out. println ("today is" + time + ", today's news is ****");}}

Then, the interface for someone to get news one day is:

Public static News getNews (String user, String time) {System. out. print ("News winner:" + user + "\ t"); System. out. print ("query new news \ t"); return new EveryDayNews (time );}

At this point, we can see that every time we get news, we will go to a new EveryDayNews object, which consumes a lot of memory. The test code is as follows:

Public static void main (String [] args) {NewsFactory. getNews ("Zhang San", "1 "). showInfo (); NewsFactory. getNews ("Li Si", "1 "). showInfo (); NewsFactory. getNews ("Wang Wu", "1 "). showInfo (); NewsFactory. getNews ("Li Si", "2 "). showInfo ();}

Test results:

We can see that all results are obtained to obtain new data, which is obviously not good, so use cache to build the Code as follows:

Static Map
 
  
NewsContainer = new ConcurrentHashMap
  
   
(); Public static News getNews (String user, String time) {System. out. print ("News winner:" + user + "\ t"); if (newsContainer. containsKey (time) {System. out. print ("get news cache \ t"); return newsContainer. get (time);} else {System. out. print ("query new News \ t"); news News = new EveryDayNews (time); newsContainer. put (time, news); return news ;}}
  
 

The cache container we use is Map, which uses time as the unique identifier variable to store news objects every day. The same test code has the following results:

From the results, we can see that when querying the news data of No. 1, only the first time is "real", and other people query the data of No. 1 again, cache data is used directly, which is equivalent to an object being cached, avoiding repeated creation and collection of objects.

String constant pool

We know that the String in Java exists in the constant pool, that is, after the String is defined, it is cached in the constant pool. When the same String is used elsewhere, it is directly used as a cache, instead of re-creating.

String str1 = new String ("abc"); String str2 = "abc"; String str3 = new String ("abc"); String str4 = "AB" + "c "; // use the equals method to compare whether the values of the strings of two objects are the same System. out. println (str1.equals (str2); // true System. out. println (str1.equals (str3); // true System. out. println (str2.equals (str3); // true System. out. println ("--------------"); // = compare whether the addresses of the two objects are the same System. out. println (str1 = str2); // false System. out. println (str1 = str3); // false System. out. println (str1 = str4); // false System. out. println (str2 = str3); // false System. out. println (str2 = str4); // true System. out. println (str3 = str4); // false

Using the equals method, we can see that all objects in str1 str2 str3 str4 are equal in the string value. However, when comparing the addresses of four objects, str1 and str3 are generated through new, so the addresses between them are different, so str1! = Str3. For str1 and str4, you can use the String output pool to explain. When this object already exists in the constant pool, no new object will be created when it is used again, directly use the cached object.

For str4 = "AB" + "c", JVM will talk about code optimization. The final result is str4 = "abc", which is exactly the same as str2.

Integer constant pool

We can start with an interview question about the constant pool of Integer. The question is as follows:

Integer i1 = Integer.valueOf(10);Integer i2 = Integer.valueOf(10);Integer i3 = Integer.valueOf(128);Integer i4 = Integer.valueOf(128);System.out.println(i1 == i2);            //trueSystem.out.println(i3 == i4);            //false

Many people have questions about i3! = I4. It seems like this. Let's take a look at the implementation of Integer. valueOf:

    public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

The comments in this document return an instance indicating that the specified int value is Integer. If you do not need to update an Integer instance, this method should be used first instead of constructing the Integer (int) method ), this method may significantly improve the space and time performance by caching frequently requested values.

This method always caches values between-128-127. In addition, it can also cache values out of this range. The above Integer. valueOf () Source Code shows that when we call the valueOf function in the range of-128-127, we actually use the value in the IntegerCache.

IntegerCache is a class that helps us cache Integer. The cache value size is controlled by-XX: AutoBoxCacheMax = size, or can be obtained by obtaining system attributes. When both i1 and i2 point to 10, i2 actually points to the data in the constant pool. Therefore, i1 = i2 is valid, but the value is not between-128-127, the new Integer () method is called, so i3! = I4.

Postscript

This is also the first article of the new year. I still feel that the status is not coming back. I mainly talk about the Yuan-sharing mode that I am familiar with and understand, I also talked about the String constant pool and Integer constant pool in my work. In the next article, I want to write about the application of the Message metadata 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.