2.1 Use design mode 23 (1)
1. Design pattern benefits;
2.1.1 Single-Case mode 23 (6)
1. The singleton pattern is an object creation pattern that produces a concrete instance of an object that ensures that only one instance of a class is produced in the system;
2. Two benefits : A, for frequently created objects, you can omit the time it takes to create the object, B, the new operation is reduced, thus the use of system memory will be reduced, reduce GC pressure, shorten the GC pause time;
3. participant in singleton mode: Singleton and user;
4. The first implementation mode : Private default constructor, static GetInstance method, this implementation is simple, reliable, but can not delay loading;
5. The second implementation: the private default constructor, when created to determine whether the object is empty, to provide a synchronous getinstance method, although the implementation can delay the loading, but the introduction of synchronization, multithreading time consuming far greater than the first implementation;
6. The third implementation: Private default constructor, private static internal class inside the creation of a private static instance, static GetInstance method; When getinstance is called, Singletonholder is loaded to initialize instance, and Because the instance is built at the time of class loading, it is inherently friendly to multithreading;
The first implementation of:
The implementation of this single example is simple and effective, but it can not delay loading;
The second implementation, introducing lazy loading:
The third Way of realization:
2.1.2 Proxy Mode 28 (17)
1. Use the proxy object to complete the user request, block the user's access to the real object;
2. Intent to use proxy mode: Security reason, Remote call, lazy load (improve system performance and reaction speed);
3. The main actors of the proxy mode: Theme interface, real topic, proxy class, client;
4. Common cases of delayed loading: Database connection, System startup, hibernate framework;
5. The core idea of lazy loading: If the component is not currently being used, you do not need to really initialize it, use a proxy object instead of its original location, as long as it is really necessary to use, it is loaded;
6. Dynamic proxy refers to the dynamic generation of proxy classes at runtime;
7. Compared with static agents, the advantages of dynamic agents: 1, do not need to write a formal package for the real topic of the same class, 2, the use of some dynamic proxy generation method can even specify the execution logic of the proxy class at run time;
8. There are 4 ways to generate a dynamic proxy class: The dynamic agent, CGLIB, javassist, ASM Library of the JDK;
9. The dynamic agent with the JDK is simple to use, but the function is weak;
Cglib and Javassist are advanced bytecode generation libraries that have better performance than JDK, and are powerful.
ASM Library Low-level bytecode generation tool, high demand for developers, performance without magnitude of promotion, maintainability is poor, only in the performance of the most demanding places to use;
The dynamic proxy implementation of JDK: Implement Invocationhandler interface, create agent through Proxy.newproxyinstance method;
Implementation of Cglib (Javassist): Implement Methodinterceptor interface, new enhancer-->setcallback-->setinterfaces-->create;
Javassist There are two ways to create: 1, use the Agent factory, 2, by using dynamic code creation;
Javassist Agent Factory Implementation: implementation of Methodinterceptor interface, new proxyfactory-->setinterfaces-->createclass--> newinstance;
Javassist is created using dynamic code, which is quite flexible and can even generate business logic at runtime;
Javassist Dynamic Code mode implementation: Classpool,ctclass;
Dynamic proxy implementations of the JDK:
Implementation of Cglib:
Javassist's agent Factory implementation:
Javassist Dynamic Java code implementation:
Performance testing of several implementation modes:
2.1.3 Hengyuan Mode 37 (8)
1. The Hengyuan model is designed to improve system performance, and the core idea is that if there are multiple identical objects in a system, you need to share a copy of the object without having to create new objects each time.
2. The main help for performance improvement of the Hengyuan mode is two points: (1), can save the cost of duplicate object creation, (2), because the number of objects created decreases, so the demand for memory is reduced, the GC pressure is reduced;
3. The main roles of the Hengyuan model are 4: Hengyuan factory, abstract Hengyuan, concrete Hengyuan class and main function;
4. In general, the Hengyuan factory maintains a list of objects that are returned directly if the requested object has been created, and if not, the object is added to the maintenance queue;
5. Typical application of the Hengyuan model: The SaaS system (software as a Service, a popular software application model at present);
6. Take the SaaS system of a personnel management system, for example, the company A, B, C are users of this SaaS system, then 3 Heng yuan instances, sufficient to meet the query request of 300 employees;
7. The maximum difference between the Hengyuan mode and the object pool is that the objects in the Hengyuan mode are not replaceable, and object pool objects are equivalent, such as database connection in database connection pool;
8. Examples of statements;
Instance:
2.1.4 Decorator Mode 40 (7)
1. Decorator mode can dynamically add object function;
2. One important design criterion is called the synthesis/aggregation multiplexing principle: Code reuse should use delegates as much as possible, rather than using inheritance, because inheritance is a tight coupling, and any changes to the parent class affect its subclasses and are not conducive to system maintenance. And the delegate is loosely coupled, as long as the interface is not changed, the change of the delegate class will not affect its upper object;
3. Decorator mode through the delegation mechanism, reuse the various components of the system, at run time, these functional components can be superimposed, so as to construct a "super object", so that they have all the functions of these components;
4. The benefits of Decorator mode: it can effectively separate the performance components and functional components, thereby improving the maintainability of the module and increasing the reusability of the module;
5. The main role of the decorator mode is 4: component interface, specific components, decorators, concrete decorators;
6. Decorator's typical case is to enhance the output, the output content into HTML, add HTTP header;
7. Many components of the JDK are implemented by the decorator model, such as OutputStream and InputStream.
Case:
Many components of the JDK are implemented by the decorator module;
2.1.5 Observer Mode 46 (5)
1. When an object's behavior depends on the state of another object, it applies to the observer pattern, and if not, it usually needs to listen to the state that the object depends on in another thread, increasing the burden of the system;
2. The significance of the observer pattern is that a single thread can be used to make an object aware of the state changes it relies on in time.
3. Observer mode can be used for event monitoring, notification, and other occasions;
4. The main role of the Observer pattern is 4: theme interface, specific subject, observer interface, specific observer;
5. JDK has a set of observer pattern implementations, the Java.util.Observable class and the Java.util.Observer interface,
Instance:
2.1.6 Value Object Mode 50 (2)
1. In the Java EE Software Development, the system module is usually layered;
2. The Value object pattern advocates encapsulating the properties of an object, passing the encapsulated object over the network, having a better interaction model, and reducing network communication data to improve system performance;
2.1.7 Business Proxy Mode 53 (2)
1. The business proxy model is to encapsulate a set of business processes composed of remote method calls, encapsulated in a proxy in the presentation layer;
2. The business agent model encapsulates some business processes in the front back-end system, providing a basic platform for performance optimization, which can not only reuse business processes in business agents, but also provide caching functions for presentation layer components as appropriate, thus reducing the number of remote method calls and reducing system pressure;
2.2 Common optimization components and methods 56 (2)
1. Components: buffering and caching;
2. Commonly used 5 optimization ideas: Pooled objects, parallel instead of serial, load balancing, time-changing space, space change time;
2.2.1 Buffering (Buffer) 56 (6)
1. Buffer is a specific area of memory;
2. The goal of the buffer zone is to mitigate performance differences between the upper and lower layers of the application and improve the performance of the system.
3. In daily life, a typical application of a buffer is a funnel;
4. The buffer can coordinate the poor performance of the upper and lower components, and when the upper component performance is better than the lower component, it can effectively reduce the waiting time of the upper component to the lower component;
5. Buffering the most common scenario is to increase the speed of I/O;
6. Case: Use buffer to enhance the animation display effect (first in memory to draw a circle, and then show it once);
Case: Using buffers to boost animation display effects
2.2.2 Caching (Cache) 59 ()
1. The cache is also a piece of memory to improve the performance of the system; The primary purpose of caching is to stage data processing results and provide the next access.
2. Case: (1), several popular browsers will cache remote pages locally, thereby reducing the number of remote HTTP accesses, (2), in the server-side system development, designers can add some core API cache, thus providing the overall performance of the system;
3. The simplest implementation of the cache is implemented using HASHMAP, there are many problems: when to clean up invalid data, how to prevent excessive cache data, resulting in memory overflow and so on;
4. A slightly better solution is to use Weakhashmap directly, which maintains a hash table using weak references, thus avoiding potential memory overflow problems, but as a professional cache, the function is slightly inadequate;
5.3 Cache Frameworks for Java: EHCache, Oscache and Jbosscache;
6. Ehcache cache is from Hibernate and is the default data caching solution for hibernate framework;
7. The Oscache cache is designed by Opensymphony and can be used to cache any object or even cache portions of a JSP or HTTP request;
8. Jbosscache is a caching framework developed by JBoss that can be used for data sharing between jboss clusters;
9. Ehcache Cache Configuration instance: Defines a default cache template, which defines two caches with names Cache1 and Cache2 respectively;
10. When to use caching: in a frequently used and heavily loaded function implementation, the cache is added to improve its performance during frequent invocation;
11. There are two ways to add a cache to a method: (1), hard-coded, add the cache processing logic in the method, the disadvantage is that the cache component and the business code tightly bound, the dependency is strong, (2), dynamic proxy, the advantage is that in the business layer, the cache operation code is completely independent and isolated, And the addition of a new function method to the cache will not affect the implementation of the original method, is a more flexible software structure;
12. Example: integer factorization;
Example: factorization of integers;
2.2.3 Object Reuse--"pool" 63 (8)
1. Object pooling: If a class is frequently requested, you do not have to generate an instance each time, you can save some instances of the class in the "Pool", and then get it directly from the pool when needed;
2. The implementation may be an array, a linked list, any collection class; Common cases are: thread pool and database connection pool;
3. Currently more extensive database connection pool components are c3p0, DBCP, PROXOOL;C3P0 is a database connection pool that accompanies hibernate and is closely connected with hibernate;
4. In the JDK, the new operation is quite efficient and does not need to worry about the performance impact of the frequent new operation on the system. However, the class constructor called by the new operation may be very time consuming, and for these objects, pooling can be considered;
5. Actual development, do not have their own implementation of the object pool, in Apache, has provided a Jakarta Commons pool object Pooling components, can be used directly, mainly: interface Objectpool, interface poolableobjectfactory;
6. The Jakarta Commons pool has a built-in definition of 3 object pools, namely Stackobjectpool, Genericobjectpool, and Softreferenceobjectpool.
7. Example: Object pool Factory;
8. Only use object pooling technology for heavyweight objects to provide system performance, using object pooling for lightweight objects may degrade system performance;
Example: Object Pool Factory
2.2.4 Parallel Substitution Serial 69 (1)
1. Java support for multithreading provides a strong guarantee for multicore computing.
2.2.5 Load Balancer 69 (8)
1. For large-scale applications, the system load may be very heavy, take the website application as an example, if a lot of concurrent, then a single computer can not bear, at this time, in order to ensure the quality of service of the application, need to use multiple computers to work together, the system load evenly distributed to each computer node;
2. The typical implementation is the Tomcat cluster: use Apache as the load allocator to turn requests to each Tomcat server;
3. When using the Tomcat cluster, there are two basic session sharing modes: Sticky session mode and copy session mode;
4. Sticky session Mode: All session information is evenly distributed across tomcat nodes for load balancing, but once a node goes down, the session it maintains will be lost, not highly available, and the same user can interact with only one tomcat. Because other Tomcat nodes do not save this user information;
5. Copy session mode: All sessions remain consistent across all nodes. When the session information on a node is modified, the session is broadcast to other Tomcat nodes to keep the session synchronized. Disadvantage is that the network is prone to busy, affecting the efficiency of the system;
6. Mature high-availability system solution: Terracotta, which is the Java open source software, a cross-JVM virtual machine dedicated to the distributed cache framework, using it can also be used to achieve tomcat session sharing;
7. Terracotta is an enterprise-class, open source, JVM layer of cluster solution, it can realize distributed object sharing, distributed cache, distributed session and other functions, can be used as load balancing, high availability solution; official website: http://terracotta.org;
8. Terracotta Example: Distributed object sharing, session sharing;
Terracotta Application cases:
2.2.6 Time Space 75 (4)
1. Because system resources are limited, in order to achieve certain performance targets within limited system resources, it is necessary to use time-for-space or space-time-changing methods.
2. Time-changing space is commonly used for embedded devices, or memory, hard disk space, etc., by using the method of sacrificing CPU, to obtain the original need more memory or hard disk space to complete the work;
3. A very simple time to change the space of the algorithm: the implementation of a, b two variable value exchange. The commonly used algorithm is to use the intermediate variables, and the introduction of additional variables means that more space is to be used, the following algorithm, you can eliminate the intermediate variables, and to achieve the purpose of variable exchange, the cost is to introduce more CPU operations;
A=a+b;
B=a-b;
A=a-b;
4. Another useful example is the support for unsigned number integers. In the Java language, unsigned integers are not supported, which means that when an unsigned byte is needed, a short substitution is required, which also means a waste of space. Using the bitwise operator to simulate unsigned byte;
2.2.7 Space Change Time 76 (3)
1. In contrast to time-space, space-time is to try to use more memory or disk space in exchange for CPU resources or network resources, etc., by increasing the memory consumption of the system to speed up the operation of the program;
2. A typical case is caching. Space change time is a design idea, in addition to caching, in some algorithms, you can also use such technology.
3. Space-time sequencing method;
Note "Java Program performance optimization makes your Java program faster and more stable" chapter II design Tuning