JAVA basics: dirty data of Java programs

Source: Internet
Author: User
JAVA basics: dirty data of Java programs-general Linux technology-Linux programming and kernel information. For details, see the following. Dirty data (Out-of-date data) refers to outdated data.

If dirty data exists in your Java program, it will bring some problems to the software system more or less. For example, you cannot apply the changed configuration in real time, the software system has some inexplicable, difficult to reproduce, and serious errors. It is very valuable to avoid dirty data as much as possible. This article hopes to help our colleagues in this regard.

Fragment 1. Dirty data in Cache Technology

/**
* A report printer is used to print a report.
*
* @ Version 1.0
* @ Author Bill
*/
Public class ReportPrinter {
/**
* Constructs a ReportPrinter instance.
*/
Public ReportPrinter (){
// Do something...
}

/**
* Prints a printable.
*
* @ Param printable the specified printable object
*/
Public void print (Printable printable ){
Graphics g = getGraphics ();
G. setFont (getReportFont (printable. getFont ());

Printable. print (g );
}

/**
* Returns the corresponding report font of a java font.
*
* @ Param javaFont the specified java font
* @ Return the corresponding report font
*/
Private Font getReportFont (font javaFont ){
Font reportFont = fontMap. get (javaFont );

If (reportFont = null ){
ReportFont = loadFont (javaFont );
FontMap. put (javaFont, reportFont );
}

Return reportFont;
}

/**
* Loads the corresponding report font of a java font.
*
* @ Param javaFont the specified java font
* @ Param the corresponding report font
*/
Protected static Font loadFont (Font javaFont ){
Font reportFont = null;

// Do something...

Return reportFont;
}

/**
* The font map (java font-> report font ).
*/
Private static HashMap fontMap = new HashMap ();
}

In Fragment 1, because the report font corresponding to loading a java font has a large overhead, the cache technology is used to avoid this overhead. This is a common way to improve performance and runs well in general. However, the design and implementation of Fragment 1 may be incomplete, because the report font corresponding to a java font may change after the system is started, this is often one of the complaints of end users. What's more terrible is that the existence of such dirty data may lead to other serious and unimaginable consequences.

How can we avoid dirty data problems caused by the use of the cache technology?

Cache data updates should be clearly defined during design, implementation, and testing:
I. Restarting the software system is necessary without considering updates to cached data;
Ii. Without considering updates to cached data, it is impossible for cached data to become dirty data (but in software systems, it is often "impossible" to become "possible" after reconstruction again and again ");
Iii. Consider cache data updates. When the source data changes, the cached data is updated in real time.

Fragment 2. Dirty data in Singleton Mode

/**
* A storage usage handler is used to query the storage usage of users.
*
* @ Version 1.0
* @ Author Bill
*/
Public class StorageUsageHandler {
/**
* Returns a StorageUsageHandler instance.
*
* @ Return the single StorageUsageHandler instance
*/
Public static StorageUsageHandler getStorageUsageHandler (){
If (handler = null ){
Handler = new StorageUsageHandler ();
}

Return handler;
}

/**
* Constructs a StorageUsageHandler instance.
*/
Private StorageUsageHandler (){
Users = Context. getAllUsers ();
}

/**
* Returns the storage sizes of all the users.
*
* @ Return the storage sizes
*/
Public long [] getSizes (){
Long sizes [] = new long [users. size ()];

For (int I = 0; I <users. size (); I ++ ){
Sizes = GetOneSize (users. get (I ));
}
}

/**
* Returns the storage size of a user.
*
* @ Param user the specified user
* @ Return the storage size
*/
Protected long getSize (User user ){
// Do something...

Return 0;
}

/**
* The StorageUsageHandler singleton.
*/
Private static StorageUsageHandler handler;

/**
* The users.
*/
Private List users;
}

Have you seen the problem?

In Fragment 2, because it is not necessary to instantiate StorageUsageHandler for the next time, the Singleton mode is used to ensure that StorageUsageHandler is instantiated only once.

When SotrageUsageHandler is instantiated, users, a class member of StorageUsageHandler, is assigned a value. Since there is no method to assign a value to users, the users that have been resident in the software system will not change. After the software system is started, operations to add, delete, or modify users often occur. Once such operations occur, users becomes dirty data and Fragment 2 cannot work normally.

How can we avoid the dirty data problems caused by using the Singleton mode?

For Singleton class members:
I. This problem does not exist for class members that are not dependent on the external aspects of the Singleton class;
Ii. if a class member that depends on the outside of the Singleton class does not have an update mechanism, it is best to remove it and retrieve it from outside the Singleton class if necessary. If this method is not feasible, A mechanism should be provided to ensure that such members have been updated before they are used.

Fragment 3. Class dirty data problems

/**
* A storage usage handler is used to query the storage usage of users.
*
* @ Version 1.0
* @ Author Bill
*/
Public class StorageUsageHandler implements AdminHandler {
/**
* Constructs a StorageUsageHandler instance.
*/
Private StorageUsageHandler (){
Users = Context. getAllUsers ();
}

/**
* Returns the storage sizes of all users.
*
* @ Return the storage sizes
*/
Public long [] getSizes (){
Long sizes [] = new long [users. size ()];

For (int I = 0; I <users. size (); I ++ ){
Sizes= GetOneSize (users. get (I ));
}
}

/**
* Returns the storage size of a user.
*
* @ Param user the specified user
* @ Return the storage size
*/
Protected long getSize (User user ){
// Do something...

Return 0;
}

/**
* Displays the storage usage of users.
*
* @ Param req the http servlet request
* @ Param res the http servlet response
*
* @ Throws IOException
* @ Throws ServletException
*/
Public void process (HttpServletRequest req, HttpServletResponse res)
Throws IOException, ServletException {

Res. setContentType ("text/html ");
Res. setHeader ("Cache-Control", "no-cache ");
Res. setHeader ("Pragma", "no-cache ");
Res. setDateHeader ("Expires", 0 );

PrintWriter writer = new PrintWriter (res. getOutputStream ());
Long sizes [] = getsizes ();
Writer. println ("");
Writer. println ("");

For (int I = 0; I <sizes. length; I ++ ){
Writer. print ("
");
Writer. print (users. get (I) + ":" + sizes);
Writer. println ("
");
}

Writer. println ("");
Writer. flush ();
Writer. close ();
}

/**
* The users.
*/
Private List users;
}

/**
* An admin servlet as a http servlet to process the admin http servlet
* Request and response.
*
* @ Version 1.0
* @ Author Bill
*/
Public class AdminServlet extends HttpServlet {
/**
* Initiates the configuration.
*
* @ Param config the servlet config
*
* @ Throws ServletException
*/
Private void initConfig (ServletConfig config) throws ServletException {
// Do something...

HandlerMap. put ("_ storage_Usage _", new StorageUsageHandler ());
}

/**
* Processes the http servlet request and response.
*
* @ Throws IOException
* @ Throws ServletException
*/
Public void service (HttpServletRequest req, HttpServletResponse res)
Throws IOException, ServletException {

AdminHandler handler = handlerMap. get (req. getParameter ("handler "));

If (handler = null ){
// Do something...

Return;
}

Handler. process (req, res );
}

/**
* The admin handler map (handler name-> handler ).
*/
Private HashMap handlerMap = new HashMap ();
}

You must have seen the problem!

In Fragment 3, because StorageUsageHandler does not follow the Singleton mode, although the StorageUsageHandler class member users can only be assigned a value when instantiating StorageUsageHandler, but in single thread mode, as long as the StorageUsageHandler instance used is newly instantiated, there is basically no problem.

The problem is that StorageUsageHandler is instantiated and stored during AdminServlet initialization. Later, unless the servlet container re-loads AdminServlet, it will not be able to re-instantiate StorageUsageHandler, nor will it be able to update the class member users of StorageUsageHandler. In this way, after a user is added, deleted, or modified, users becomes dirty data.

How can we avoid dirty data problems caused by class usage?

I. This problem does not exist for class members that have no dependency with the external class;
Ii. There is no update mechanism for class members that depend on the outside of the class. It is best to remove it and obtain it directly from outside the class if necessary. If this method is not feasible, a mechanism should be provided to ensure that the class members have been updated before using the class members; if this method is not feasible, clearly describe the usage of the class to prevent improper use of the class.

Section

The preceding three examples illustrate three common dirty data problems. In fact, the dirty data problems in Java programs exist in a variety of forms. Therefore, in the process of design, implementation, testing, and refactoring, remember (Keep in mind) it is very important to avoid dirty data. We can check Java programs at various levels, such as systems, subsystems, classes, and class members.
"Only one thing is good" is the best interpretation of simplicity, which also best interprets the functional orthogonal of the software system. However, in the process of object-oriented software development, it is not enough to ensure the orthogonal only in terms of functions. We should also try to ensure the orthogonal in terms of data storage. Of course, considering performance and other factors, it is difficult to ensure the orthogonal nature of data storage. A mechanism should be provided for data storage that undermines this rule to ensure the real-time performance of the data used.
Related Article

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.