Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/vir007/public_html/geekmantra.com/contact/connect.php on line 2
Free Online Most Freaky Tutorials,Most Freaky Programming Tutorials,Most Freaky notes
GeekMantra
Search Site

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/vir007/public_html/geekmantra.com/contact/connect.php on line 2
J2SE [Java 2 Standard Edition]
Core Java Introduction
Exception Handling
Collection & Util Classes
Multithreading
Input & Output Streams
Applet
Adwance Windows Toolkit (AWT)
Swings (Adwance GUI)
Event Handling
Java Networking
Remote Method Invocation (RMI)
Java Database Connectivity (JDBC)
J2EE [Java 2 Enterprise Edition]
Java 2 Enterprise Edition Intoduction (J2EE)
Server Side Programming (Servlet)
Java Server Pages (JSP)
Enterprise Java Bean
MVC Framework (Struts)
Advance Framework (Springs)
Object-relational mapping (Hibernate)
eXtensible Markup Language (XML)
Asynchronous JavaScript and XML (AJAX)
Miscellneous
Monthly News Letter
Free SCJP Samples
Interviews Questions For Freshers
Interviews Questions For Experinced
Most Visited Links
Most Freaky Links
Advertisements

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/vir007/public_html/geekmantra.com/contact/connect.php on line 2

Performance Tuning Tips-Java

I like this stuff on Performance tuning. Here are some random thoughts in no particular order:

1) Measure don`t guess - Often we guess wrong on what code to tune and end up wasting our time tuning code that makes no overall impact. Measure performance and go for those small sections of code that consume the most time. Measure your performance improvements and repeat the process.

2) Measure in production - You have no idea how your system is used unless you are looking at real user interactions. For example say you have 2 pages that each take 1 second to execute. In load tests you assume that each page will be hit the same number of times, but users think otherwise. Users may hit one of the pages orders of magnitudes more than the other one. By measuring in production you learn which page should be tuned first. Usually master pages are hit more than detail pages.

3) Build performance measurement collection into your application from the start
- Web performance is difficult to understand looking in from the outside. Measure overall page response time and calls to external systems like jdbc (see the jamon Servlet filter mentioned below)

4) Use the JAMon Servlet filter, it is your friend
- I must admit I wrote this software and so I am biased, but by simply adding a few lines to your web.xml and making jamonadmin.jsp accessible you get many performance statistics such as: page hits, avg time, min time, max time. You also get concurrency stats like which pages are currently executing, what were the max simultaneous invocations per page. You also have correlations between performance and concurrency i.e. this is a measure of scalability.

A few more things. JAMon is fast enough to be used in production systems (pretty much no overhead), it is part of your app so no special installation of software, it can monitor other things such as jdbc too, and it is free. Because JAMon is part of your application it moves from dev/test/prod with no server environmental changes.

5) It`s probably the database - A recent application that I worked on took 95% of its execution time executing SQL. Of the 50 or so sql statements 80% was spent on 2 queries. These queries were tuned by adding indexes and the application zipped along with NO code changes. Only 5% of the application was doing anything in java code. I find this to be pretty typical. By the way your denormalized database can often not perform as well due to having fat tables that must perform more IO. Indexes are your friends.

6) If it`s not the database it is probably some other IO -
IO (database, network, file) will usually be your performance culprits, and not your java code. Tuning your jdbc driver and network may help more than tuning your java code.

7) Learn to write good SQL - This is probably more important than any Java P&T tricks you can learn.

8) Some performance truisms:
- 80% of a programs execution time is caused by 20% of the code. Your job as a tuner is to find the 20% of your code and leave the other 80% alone.
- "More computing sins are committed in the name of efficiency than for any other single reason-including blind stupidity" - W.A. Wulf
- "...premature optimization is the root of all evil." - Donald Knuth
9) Be wary of slow home pages - Home pages are often heavily hit. Have them due minimal work or even just display a menu. One app I work with has a home page that takes 2 seconds, but I am never interested in that page and immediately go elsewhere.

10) Don`t micro tune - An example of micro tuning is when you have a page that takes 1 second to execute, and you notice that you can make a piece of code that takes 20 ms. down to 10 ms. You`ve double the performance of this code which sounds impressive, but have trimmed performance of your overall page a trivial amount (from 1000 ms. to 990 ms). This tuning was a waste of time. Your time would have been better spent drinking a beer. Look for changes that give you the biggest bang for your tuning buck.

11) There are bad Performance Tuning Questions - The most common performance tuning questions I see on the java forums, are purely academic and make no substantive difference in a real program. Questions like: "Are statics faster than instance variables?", "Are local variables faster than instance variables?", "Are HashMaps faster than Vectors?", "Are while loops faster than for loops?",...

12) It`s not just execution time but frequency
- If you don`t know the frequency of execution (hits) then you wouldn`t know which page to tune of 2 pages that take 1 second to execute. If you know one is executed 10 times a day and the other 10,000 times a day you would.

13) Good design is your best performance tuning tool - Good designs are easy to change and so easy to make faster. Good design involves having a way to measure application performance.

14) If your page takes more than a couple seconds it probably needs tuning - Users are that patient and will move to another site or start mashing on the refresh button if your page is slow. Both outcomes won`t be to your liking.

15) Your biggest scalability problem may be one user getting impatient and hitting refresh before the page returns - In applications I have seen users have many outstanding requests and so one user can single handedly bring your site down unless you build protection for this into your app from the start. (The JAMon Servlet filter can detect this problem)

16) Don`t return 10,000 rows - The bad news is browsers are slow in displaying so many rows. The good news is that your users really don`t want to see so much data even if they say they do. It is your job as a developer to find out what they really want and give that capability to them.

17) Java is fast, very fast
- Despite java`s still lingering reputation of being slow it is very fast. I can execute a method on my old clunker pc 60,000,000 times a second. Even object creation and garbage collection are quite fast.

18) Google is your best friend - Google knows anything you wish to learn about performance tuning and any other topic

What is the difference between an application server and a Web server?

An application server is technology where developers can create, test, and execute application components. Application servers are typically J2EE-based, running EJBs or other Java components. Application servers are designed to create true applications with complex business logic, and have scalability features such as load balancing, fail-over, and process distribution. In other words, it`s primarily a development environment.In contrast, Web servers are technology designed to create and deploy Web site, serving up content more so than applications. They both use Web interfaces, but Web servers are more about the interface than the back-end logic. In other words, Web servers serve up content.
As time moves on Web servers are looking more like application server, as they adopt their functionality. I can understand the confusion.
Let`s examine each in more detail.

The Web server
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Understand that a Web server`s delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn`t provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. The server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging.

While a Web server may not itself support transactions or database connection pooling, it may employ various strategies for fault tolerance and scalability such as load balancing, caching, and clustering—features oftentimes erroneously assigned as features reserved only for application servers.

The application server
As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.
In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.

Application server and a Web server An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the site will provide a form with which you can choose a product. When you submit your query, the site performs a lookup and returns the results embedded within an HTML page. The site may implement this functionality in numerous ways. I`ll show you one scenario that doesn`t use an application server and another that does. Seeing how these scenarios differ will help you to see the application server`s function.

Scenario 1: Web server without an application server
In the first scenario, a Web server alone provides the online store`s functionality. The Web server takes your request, then passes it to a server-side program able to handle the request. The server-side program looks up the pricing information from a database or a flat file. Once retrieved, the server-side program uses the information to formulate the HTML response, then the Web server sends it back to your Web browser.

To summarize, a Web server simply processes HTTP requests by responding with HTML pages.

Scenario 2: Web server with an application server
Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However, you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the script knowing how to look up the data and formulate a response, the script can simply call the application server`s lookup service. The script can then use the service`s result when the script generates its HTML response.

In this scenario, the application server serves the business logic for looking up a product`s pricing information. That functionality doesn`t say anything about display or how the client must use the information. Instead, the client and application server send data back and forth. When a client calls the application server`s lookup service, the service simply looks up the information and returns it to the client.

By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more reusable between applications. A second client, such as a cash register, could also call the same service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information is embedded within the HTML page.

To summarize, in Scenario 2`s model, the Web server handles HTTP requests by replying with an HTML page while the application server serves application logic by processing pricing and availability requests.

Caveats
Recently, XML Web services have blurred the line between application servers and Web servers. By passing an XML payload to a Web server, the Web server can now process the data and respond much as application servers have in the past.

Additionally, most application servers also contain a Web server, meaning you can consider a Web server a subset of an application server. While application servers contain Web server functionality, developers rarely deploy application servers in that capacity. Instead, when needed, they often deploy standalone Web servers in tandem with application servers. Such a separation of functionality aids performance (simple Web requests won`t impact application server performance), deployment configuration (dedicated Web servers, clustering, and so on), and allows for best-of-breed product selection.

What is Singleton Class

In software engineering, the singleton design pattern is used to restrict instantiation of a class to one
object. This is useful when exactly one object is needed to coordinate actions across the system.
Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.
It is also considered an anti-pattern since it is often used as a euphemism for global variable. Before
designing a class as a singleton, it is wise to consider whether it would be enough to design a normal class
and just use one instance.

The singleton pattern is implemented by creating a class with a method that creates a new instance of the
object if one does not exist. If an instance already exists, it simply returns a reference to that object. To
make sure that the object cannot be instantiated any other way, the constructor is made either private or
protected. Note the distinction between a simple static instance of a class and a singleton. Although a
singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or
resources until needed.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to
execute the creation method at the same time when a singleton does not yet exist, they both must check for
an instance of the singleton and then only one should create the new one. If the programming language has
concurrent processing capabilities the method should be constructed to execute as a mutually exclusive
operation.

The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is
being instantiated.

Here is the Example of Singleton Class with Unique DataBase Object.

package com;

import java.sql.*;

   public class Connect
   {
       private Connection conn = null;
       private static Connect obj=null;
       
       private Connect()
       {
       }
       public Connection getConnection()
       {
           try
           {
               String userName = "root";
               String password = "";
               String url = "jdbc:mysql://localhost:3306/geekmantra";

               Class.forName("com.mysql.jdbc.Driver");

               conn = DriverManager.getConnection(url, userName, password);

               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               System.err.println ("Cannot connect to database server-"+e);
           }
          return conn;
       }

       public void closeConnection()
       {
           if (conn != null)
           {
               try
               {
                   conn.close ();
                   System.out.println ("Database connection terminated");
               }
               catch (Exception e) { /* ignore close errors */ }
           }
        }
  
            public static Connect getData()
         {
            if(obj==null)
            {
                obj=new Connect();
            }
            return obj;               
         }
 
   }