Wednesday, April 27, 2011

An event handling example using inner classes


class FrameMenubar  {
   //Other methods
   private void createGUI(){
      //Other components
      MenuItem about = new MenuItem("About");
      about.addActionListener(new AboutAdapter());
      // other components
   }
   class AboutAdapter implements ActionListener{
      OkBox aboutBox;
      public void actionPerformed(ActionEvent e){
         String topString = new String(copyRight+" "+author+"\n");
         String midString = new String(aboutMidText+"\n");
         //OkBox whose code not shown here is a subclass of
         //java.awt.Dialog. Some variables passed to the
         //OkBox constructor are declared in the enclosing
         //classes.FrameMenuApp is the top-most class which
         //is not shown.
         aboutBox = new OkBox(FrameMenuApp.this,
                              256, // width
                              256, // height
                              aboutBoxTitle,
                              topString+midString,
                              false);
         aboutBox.addActionListener(
            new ActionListener() {//Anonymous class
               public void actionPerformed(ActionEvent e){
                  aboutBox.dispose();
               }
            }
          );
          aboutBox.show();
      }
   }//End of AboutAdapter
}//End of FrameMenubar

Example of an annonymous class which implements an interface.


Button dispBtn = new Button("Display");
dispBtn.addActionListener(
   new ActionListener(){
      public void actionPerformed(ActionEvent e){
         displayImage();
      }
   }
);

Extending an inner class in a sub class of the top level class.


class OuterExtended extends OuterMost{
   String str = new  String("OuterExtended");
   class InnerOneExtended extends InnerOne{
      String str = new String("InnerOneExtended");
      class NestedExtended extends InnerNestedOne{
         String str = new String("NestedExtended");
         NestedExtended(int id){
            super(id);
         }
         public void printAllClasses( ){
            System.out.println("Class name: "+ this.str);
            System.out.println("Class name: "+
                                InnerOneExtended.this.str);
            System.out.println("Class name: "+
                                OuterExtended.this.str);
            super.printAllClasses();
         }
      } //End of NestedOneExtended
   }// End of InnerOneExtended
   public static void main(String args[]){
      OuterExtended outerE = new OuterExtended();
      InnerOneExtended innerE = outerE. new InnerOneExtended();
      InnerOneExtended.NestedExtended nestedE = innerE .new NestedExtended(200);
      nestedE.printAllClasses();
   }
} //End of OuterExtended

Extending an inner class outside its enclosing scope.


class InnerExtended extends OuterMost.InnerOne.InnerNestedOne{
   String str = new String("InnerExtended");
   public InnerExtended(OuterMost.InnerOne ione, int id){
      ione.super(id);//creating the inner class instance
   }
   public void printName(){
      System.out.println("Class name: "+ this.str );
   }
   public static void main(String arg[]){
      OuterMost outer = new OuterMost();
      OuterMost.InnerOne inner = outer. new InnerOne();
      InnerExtended ext = new InnerExtended(inner, 100);
      ext.printName();
      ext.printAllClasses();
   }
}

Top level and inner class examples


// A top-level class
class OuterMost{
   private String str = new  String("OuterMost");
   public void printName(){
      System.out.println("Class name: "+ str);
   }
   //A static class
   static class StaticNestedOne{
      static String str = new String("StaticNestedOne");
      static void printName(){
         System.out.println("Class name: "+str);
      }
      static class StaticNestedTwo{
         static String str = new String("StaticNestedTwo");
         static void printName(){
            System.out.println("Class name: "+str);
         }
      }//End of StaticNestedTwo
   } //End of StaticNestedOne
   //An inner class
   class InnerOne{
      public String str1 = new String("InnerOne");
      //An interface within an inner class
      public interface IDPrinter {
         static final int BASE_VALUE=100;
            public void printID();
      }
      public void printName(){
         System.out.println("Class name: "+ this.str1 );
      }
      //Nested inner class that implements an interface
      class InnerNestedOne implements IDPrinter{
         int id;
         protected String str = new String("InnerNestedOne");
         InnerNestedOne(int id){
            this.id = id;
         }
         public void printName(){
            System.out.println("Class name: "+ this.str);
         }
         public void printID(){
            System.out.println(BASE_VALUE+id);
         }
         public void printAllClasses(){
            printName(); //local method
            InnerOne.this.printName(); //enclosing class method
            //creates an object using a private
            //inner class in the outer scope
            InnerTwo innerTwo = new InnerTwo();
            innerTwo.printName();
            OuterMost.this.printName(); //top level method
            StaticNestedOne.printName();
            StaticNestedOne.StaticNestedTwo.printName();
         }
      }// End of InnerNestedOne
   }//End of InnerOne
   // A private inner class
   private class InnerTwo{
      public String str = new String("InnerTwo");
      public void printName(){
         System.out.println("Class name: "+ this.str);
      }
   }// End of InnerTwo
}//End of OuterMost

//A class that uses OuterMost and it's nested and inner classes
class Outside{
   public static void main(String arg[]){

      OuterMost.StaticNestedOne.printName();
      OuterMost.StaticNestedOne.StaticNestedTwo.printName();

      OuterMost outer = new OuterMost();
      OuterMost.InnerOne inner = outer. new InnerOne();
      inner.printName();

      OuterMost.InnerOne.InnerNestedOne innerNested = inner. new InnerNestedOne(10);
      innerNested.printName();
      innerNested.printAllClasses();
   }
}// End of Outside

rewritten using inner classes


import java.awt.*;
   import java.awt.event.*;
   //Top-most class
   class ImageViewer {
      public static final void main(String[] args){
         ImageViewer im = new ImageViewer();
      }
      public ImageViewer(){
         CommandPanel cp = new CommandPanel();
      }
      public void displayImage(){
         // Code to display an image
      }
      class CommandPanel extends Frame{
         CommandPanel(){
            createGUI();
         }
         private void createGUI(){
            setLayout(new FlowLayout());
            Button dispBtn = new Button("Display");
            DisplayCommand dispC = new DisplayCommand();
            dispBtn.addActionListener(dispC);
            // Other components
            add(dispBtn);
            pack();
            setSize(100,100);
            setVisible(true);
         }
         class DisplayCommand implements ActionListener {
            public void actionPerformed(ActionEvent e){
               displayImage();
            }
         } // End of DisplayCommand
      } // End of CommandPanel
    } // End of ImageViewer

An example without using inner classes


import java.awt.*;
   import java.awt.event.*;
   //Top-most class
   class ImageViewer {
      public static final void main(String[] args){
         ImageViewer im = new ImageViewer();
      }
      public ImageViewer(){
         CommandPanel cp = new CommandPanel(this);
      }
      public void displayImage(){
         // Code to display an image
      }
   }
   // Creates GUI
   class CommandPanel extends Frame{
      ImageViewer viewer;
      CommandPanel(ImageViewer vw){
         viewer = vw;
         createGUI();
      }
      private void createGUI(){
         setLayout(new FlowLayout());
         Button dispBtn = new Button("Display");
         DisplayCommand dispC = new DisplayCommand(viewer);
         dispBtn.addActionListener(dispC);
         // Other components
         add(dispBtn);
         pack();
         setSize(100,100);
         setVisible(true);
      }
   }
   //Adapter class to handle events
   class DisplayCommand implements ActionListener {
      ImageViewer viewer;
      public DisplayCommand(ImageViewer vw){
         viewer = vw;
      }
      public void actionPerformed(ActionEvent e){
         viewer.displayImage();
      }
   }

Coding standards for java - Presentation Transcript


Coding standards for java - Presentation Transcript

  1. Coding Standards for JavaAn Introduction
  2. Why Coding Standards are Important? Coding Standards lead to greater consistency within your code and the code of your teammates. Easier to understand Easier to develop Easier to maintain Reduces overall cost of application
  3. Components of Java Source File /* * Copyright notice */ package java.awt; import java.awt.peer.CanvasPeer; /** * class description * * @version 1.10 04 Oct 1996 * * @author First name Last name */ public class ColorPickerPanel { /* A class implementation comment can go here. */ /**  *class variables – doc comment */ public static Integer colorVariant; /**  *instance variables – doc comment */ private String colorCode; Beginning Comments Package and Import Statements Class/interface documentation comment (/**...*/) class or interface statement Class/interface implementation comment (/*...*/), if necessary Class (static) variables Instance variables
  4. Components of Java Source File continued… /**  *default constructor */ public ColorPickerPanel() { colorVariant = 11; colorCode = #FFFFFF; } /**  *two argument constructor */ public ColorPickerPanel(Integer colorVariant, String colorCode) { this.colorVariant = colorVariant; this.colorCode = colorCode; } /**  *@retrun the color code */ public String getColorCode() { return colorCode; } /**  *@param Integer the color variant */ public void setColorVariant(Integer colorVariant) { ……… ……… } } Indentation Constructors Blank line Documentation comments Methods
  5. Comments /** * class description * @version 1.10 04 Oct 1996 * @author First name Last name */ public class ColorPickerPanel { /* A class implementation comment can go here. */ /* private static final String DEFAULT_COLOR = “#FFFFFF” private static final int DEFAULT_VARIANT = 0; */ /**  *class variables – doc comment */ public static Integer colorVariant; /**  *instance variables – doc comment */ private String colorCode; /**  *@param Integer the color variant */ public void setColorVariant(Integer colorVariant) { if (colorVariant == 0) { colorCode = “#000000”; /* set the color to black*/ } else { colorCode = “#FFFFFF”; // set the color to while } } } Documentation Comments Implementation Comments Single Line Comments Block Comments Trailing Comments End-of-Line Comments
  6. Naming Conventions What Makes Up a Good Name? Use full English descriptors  For example, use names like firstName, grandTotal, or CorporateCustomer Use terminology applicable to the domain Banking domain - Customer, Software services domain - Client Use mixed case to make names readable Avoid long names (< 15 characters is a good idea) User abbreviations sparingly Capitalize the first letter of standard acronym
  7. Naming Conventions Continued… Classes / Interfaces –  Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Methods –  Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Variables –  Variables should be nouns, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Class Constants –  Class Constants should be all uppercase with words separated by underscores (“_”).
  8. Blank Spaces Before / After Parenthesis – A keyword followed by a parenthesis should be separated by a space. while_(true)_{ ... } A blank space should appear after commas in argument lists. All binary operators except . should be separated from their operands by spaces.  a = (a + b) / (c * d); The expressions in a for statement should be separated by blank spaces. for (expr1; expr2; expr3) Casts should be followed by a blank. User x = (User) anObject; blank spaces
  9. Returning Values Try to make the structure of your program match the intent. Example: if (booleanExpression) { return TRUE; } else { return FALSE; } should instead be written as return booleanExpression;
  10. Ternary Operator (?:) Use Ternary Operator for conditional assignment Example: Int x; If (expression) { x = 9; } else { x = 0; } can be written as x = (expression) ? 9 : 0;
  11. much more to learn … References Google…
  12. Ambler’s Law of Standards Industry standards > organizational standards > project standards > personal standards > no standards
  13. so, what is the lesson to learn? Whenever possible, reuse standards and guidelines, don’t reinvent them
  14. Static Code Analysis Static code analysis is the analysis of computer software that is performed without actually executing programs built from that software. (analysis performed on executing programs is known as dynamic analysis) In most cases the analysis is performed on some version of the source code and in the other cases some form of the object code. The term is usually applied to the analysis performed by an automated tool, with human analysis being called program understanding, or code review. Some of automated SCA Tools – PMD, AppPerfect, FindBugs, IntelliJ IDEA etc.
  15. PMDhttp://pmd.sourceforge.net/ PMD scans Java source code and looks for potential problems like: Possible bugs - empty try/catch/finally/switch statements Dead code - unused local variables, parameters and private methods Suboptimal code - wasteful String/StringBuffer usage Overcomplicated expressions - unnecessary if statements, for loops that could be while loops Duplicate code - copied/pasted code means copied/pasted bugs
  16. PMD – Rule Set for SCAhttp://pmd.sourceforge.net/rules/index.html Basic JSP rules NoLongScripts: Scripts should be part of Tag Libraries, rather than part of JSP pages.  NoScriptlets: Scriptlets should be factored into Tag Libraries or JSP declarations, rather than being part of JSP pages.  NoInlineStyleInformation: Style information should be put in CSS files, not in JSPs. Therefore, don't use <B> or <FONT> tags, or attributes like "align='center'".  NoClassAttribute: Do not use an attribute called 'class'. Use "styleclass" for CSS styles.  NoJspForward: Do not do a forward from within a JSP file. 
  17. AppPerfect Java Code Test AppPerfect Java Code Test is a static Java code analysis software designed to perform the following two key tasks: Automate Java code review and Enforce Good Java Coding Practices.  AppPerfect Code Test analysis your Java and Java Server Pages (JSP) source code and applies over 750 Java coding rules to apply the collective knowledge of leading experts in the Java programming field to your code. Some Rules – Avoid method calls in loop Declare methods not using instance variables static User equals method instead of equality operator Etc.
  18. AppPerfect Java Code Testa screen shot
  19. Queries!

JDBC goals


 The goals of best practices for JDBC programming are maintainability, portability and performance.
  • Maintainability refers to the ease with which developers can understand, debug and modify JDBC code that they didn't write.
  • Portability refers to the ease with which JDBC code can be used with multiple databases. It turns out that JDBC doesn't make database programming as platform independent as I'd like. In addition, I consider portability a noble goal even if you have no current plans to support multiple databases. Who knows how long your code will be around and what kinds of changes will have to be made to it?
  • Performance refers to optimizing the speed and/or memory needed to run JDBC code.

Information Servlet


Wednesday, April 6, 2011

programs :Lang_Util

Equals
public class Equals{
public static void main(String args[]){
    Calculator c1=new Calculator();
    Calculator c2=c1;//new Calculator();
    if(c1==c2){
       System.out.println("c1==c2");
    }else{
    System.out.println("c1!=c2");
    }
    if(c1.equals(c2)){
       System.out.println("c1.equals(c2)");
    }else{
      System.out.println(" c1 not equal to (c2)");
    }
}
}
hashCode
public class hashCode{
public static void main(String args[]){
    Calculator c1=new Calculator();
    Calculator c2=new Calculator();
        int i=c1.hashCode();
       System.out.println("c1.hashCode() : "+c1.hashCode());
       System.out.println("c2.hashCode() : "+c2.hashCode());
       Demo d=new Demo();
       System.out.println("this.hashCode() : "+d.hashCode());   
          System.out.println("Result : "+ c1.add(10,20));
       c1=c2;
       System.out.println("c1.hashCode() : "+c1.hashCode());
       System.out.println("c2.hashCode() : "+c2.hashCode());
       if(c1.hashCode()==i)
              System.out.println("Result : "+ c1.add(10,20));
       else
                 System.out.println("C1 is unknown Object");
}
}

PriEquals
public class PriEquals{
public static void main(String args[]){
    int c1=100;
    int c2=1000;
    if(c1==c2){
       System.out.println("c1==c2");
    }else{
    System.out.println("c1!=c2");
    }
    /*if(c1.equals(c2)){
       System.out.println("c1.equals(c2)");
    }else{
      System.out.println(" c1 not equal to (c2)");
    }*/
}
}



Equals

public class Equals{
public static void main(String args[]){
    Calculator c1=new Calculator();
    Calculator c2=c1;//new Calculator();
    if(c1==c2){
       System.out.println("c1==c2");
    }else{
    System.out.println("c1!=c2");
    }
    if(c1.equals(c2)){
       System.out.println("c1.equals(c2)");
    }else{
      System.out.println(" c1 not equal to (c2)");
    }
}
}

Tuning Garbage Collection with the 1.3.1 Java Virtual Machine

Introduction

The Java 2 Platform is increasingly used for large server applications such as web services.  These applications demand scalability, and directly benefit from large numbers of threads, processors, sockets and memory.  Yet 'big iron' performance has a reputation as an art form, requiring special expertise beyond what is needed for performance on smaller systems.  Fortunately, the Java Virtual Machine (JVM)* and Solaris operating environment provide effective implementations of threads, I/O and memory management.  This document addresses a common speed bump on the road to scalable high performance: poorly tuned garbage collection (GC).

Amdahl observed that most workloads cannot be perfectly parallelized; some  portion is always sequential and does not benefit from parallelism.   This is also true for the Java 2 Platform.  In particular, JVMs up to and including version 1.3.1 do not have parallel garbage collection, so the impact of GC on a multiprocessor  system grows relative to an otherwise parallel application. The graph below models an ideal system that is perfectly scalable with the exception of GC.  The top line (red) is an application spending only 1% of the time in GC on a uniprocessor; this translates into more than 20% loss in throughput at 32 processors.  At 10%, not considered an outrageous amount of time in GC in uniprocessor applications, more than 75% of throughput is lost when scaling up. 

This demonstrates that issues that appear lost in the noise when developing on small systems may become principal bottlenecks when scaling up.  The silver lining is that small improvements in such a bottleneck can produce large gains in performance.  For a sufficiently large system it becomes well worthwhile to tune garbage collection.

This document is written from the perspective of 1.3.1 JVM on the Solaris (SPARC Platform Edition) operating environment, because that platform provides the most scalable hardware/software Java 2 platform today.  However, the descriptive text applies to other supported platforms, including Linux, Microsoft Windows, and the Solaris (Intel Architecture) operating environment, to the extent that scalable hardware is available.  Although command line options are consistent across platforms, some platforms may have different defaults than described here.

Generations

One of Java 2 Platform's great strengths is that it shields the substantial complexity of memory allocation and garbage collection from the developer.  However, once GC has become the principal bottleneck, it becomes worth understanding aspects of this hidden implementation.  Garbage collectors make assumptions about the way applications use objects, and these are reflected in tunable parameters that can be adjusted for improved performance without sacrificing the power of the abstraction.

An object is garbage when it can no longer be reached from any pointer in the running program.  The most straightforward garbage collection algorithms simply iterate over every reachable object; any objects left over are then known to be garbage.  This approach takes time proportional to the number of living objects, which is prohibitive for large applications maintaining lots of living data.

The 1.3 JVM incorporates a number of different garbage collection algorithms that are combined using generational collection.  While naive garbage collection examines every living object in the heap, generational collection exploits several empirically observed properties of most applications to avoid extra work.

The most important of these properties is infant mortality.  The blue area in the diagram below is a typical distribution for the lifetimes of objects.  The sharp peak at the left represents objects that can be reclaimed shortly after being allocated.  Iterator objects, for example, are often alive for the duration of a single loop. 

Some objects do live longer, and so the distribution stretches out to the the right.  For instance, there are typically some objects allocated at initialization that live until the process exits.  Between these two extremes are objects that live for the duration of  some intermediate computation, seen here as the lump to the right of the infant mortality peak.  Some applications have very different looking distributions, but a surprisingly large number possess this general shape.  Efficient collection is made possible by focusing on the fact that a majority of objects die young.

To do this, memory is managed in generations: memory pools holding objects of different ages.  Garbage collection occurs in each generation when it fills up; these collections are represented on the diagram above with vertical bars.  Objects are allocated in eden, and because of infant mortality most objects die there.  When Eden fills up it causes a minor collection, in which some surviving objects are moved to an older generation.  When older generations need to be collected there is a major collection that is often much slower because it involves all living objects. 

The diagram shows a well-tuned system in which most objects die before they survive to the first garbage collection.  The longer an object survives, the more collections it will endure and the slower GC becomes.  By arranging for most objects to survive less than one collection, garbage collection can be very efficient.  This happy situation can be upset by applications with unusual lifetime distributions, or by poorly sized generations that cause collections to be too frequent. 

The default garbage collection parameters were designed to be effective for most small applications.  They aren't optimal for many server applications.  This leads to the central tenet of this document:

If GC has become a bottleneck, you may wish to customize the generation sizes.  Check the verbose GC output, and then explore the sensitivity of your individual performance metric to the GC parameters.

Types of collection

  Each generation has an associated type of garbage collection that can be  configured to make different algorithmic time, space and pause tradeoffs.   In 1.3, the JVM implements three very different garbage collectors:
  1. Copying (sometimes called scavenge): this collector very efficiently moves objects between two or more generations.  The source generations are left empty, allowing remaining dead objects to be reclaimed quickly.  However, since it requires empty space to operate, copying requires more footprint.  In 1.3.1 copying collection is used for all minor collections.
  2. Mark-compact: this collector allows generations to be collected in place without reserving extra memory; however, compaction is significantly slower than copying.  In 1.3.1 mark-compact is used for major collections.
  3. Incremental (sometimes called train): this collector is used only if -Xincgc is passed on the command line.  By careful bookkeeping, incremental GC collects just a portion of the old generation at a time, trying to spread the large pause of a major collection over many minor collections.  However, it is even slower than mark-compact when considering overall throughput.
Since copying is very fast, a tuning goal is to collect as many objects as possible by copying rather than by compaction or incremental collection.

The default arrangement of generations looks something like this.  
At initialization, a maximum address space is virtually reserved but not allocated physical memory unless it is needed.  The complete address space reserved for object memory can be divided into the young and old generations.

The young generation consists of eden plus two survivor spaces .  Objects are initially allocated in eden.  One survivor space is empty at any time, and serves as the destination of the next copying collection of any living objects in eden and the other survivor space.  Objects are copied between survivor spaces in this way until they age enough to be tenured (copied to the old generation.)

(Other virtual machines, including the production JVM version 1.2 for the Solaris operating environment, used two equally sized spaces for copying rather than one large eden plus two small spaces.  This means the options for sizing the young generation are not directly comparable; see the Performance FAQ for an example.)

The old generation is collected in place by mark-compact.  One portion called the permanent generation is special because it holds all the reflective data of the JVM itself, such as class and method objects. 

Performance considerations

There are two primary measures of garbage collection performance.  Throughput is the percentage of total time not spent in garbage collection, considered over long periods of time. Throughput includes time spent in allocation (but tuning for speed of allocation is generally not needed.) Pauses are the times when an application appears unresponsive because garbage collection is going on.

Users have different requirements of garbage collection.  For example, some consider the right metric for a web server to be throughput, since pauses during garbage collection may be tolerable, or simply obscured by network latencies.  But for an interactive graphical program, even short pauses may upset the user experience.

Some users are sensitive to other considerations.  Footprint is the working set of a process, measured in pages and cache lines.  On systems with limited physical memory or many processes, footprint may dictate scalability.  Promptness is the time between when an object becomes dead and when the memory becomes available, an important consideration for distributed systems including RMI.

In general, a particular generation sizing chooses a trade-off between these considerations.  For example, a very large young generation may maximize throughput, but does so at the expense of footprint and promptness.  Pauses can be minimized by using a small young generation and incremental collection, at the expense of throughput.

There is no one right way to size generations; the best choice is determined by the way the application uses memory as well as user requirements.  For this reason the JVM's default GC choices may not be optimal, and may be overridden by the user in the form of command line options below.

Measurement

Throughput and footprint are best measured using metrics particular to the  application.  For example, throughput of a web server may be tested using a client load generator, while footprint of the server might be measured on the Solaris operating environment using the pmap command.   On the other hand, pauses due to GC are easily estimated by inspecting the  diagnostic output of the JVM itself.

The command line argument -verbose:gc prints information at every collection.  For example, here is output from a large server application:

  [GC 325407K->83000K(776768K), 0.2300771 secs]
  [GC 325816K->83372K(776768K), 0.2454258 secs]

  [Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections and one major one.  The numbers before and after the arrow indicate the combined size of live objects before and after the GC.   (After minor collections the count includes objects that aren't necessarily alive but can't be reclaimed, either because they are directly alive, or because they are within or referenced from the old generation.)  The number in parenthesis is the total available space, which is the total heap minus one of the survivor spaces.

Sizing the generations

  A number of parameters affect generation size.  This diagram illustrates  the ones most important to tuning the 1.3.1 JVM.  Many parameters are  actually ratios x:y, and these are depicted with black (representing    x) and grey (representing y) size bars:

Total heap

Since collections occur when generations fill up, throughput is inversely proprotional to the amount of memory available.  Total available memory is the most important knob affecting GC performance. 

By default, the JVM grows or shrinks the heap at each collection to try to keep the proportion of free space to living objects at each collection within a specific range.  This target range is set as a percentage by the parameters -XX:MinHeapFreeRatio=<minimum> and -XX:MaxHeapFreeRatio=<maximum>,  and the total size is bounded below by -Xms and above by -Xmx .  The default parameters for the Solaris (SPARC Platform Edition) operating environment are shown in this table:

-XX:MinFreeHeapRatio= 40
-XX:MaxHeapFreeRatio= 70
-Xms 3584k
-Xmx 64m

Large server apps often experience two problems with these defaults.  One is slow startup, because the initial heap is small and must be resized over many major collections.  A more pressing problem is that the default maximum heap size is unreasonably small for most server applications.  The rules of thumb for server applications are:

Unless you have problems with pauses, try granting as much memory as possible to the JVM.  The default size (64MB) is often too small.

Setting -Xms and -Xmx to the same value increases predictability by removing the most important sizing decision from the JVM.  On the other hand, the JVM can't compensate if you make a poor choice.

Be sure to increase the memory as you increase the number of processors, since allocation can be parallelized, but GC is not parallel.

The young generation

The second most influential knob is the proportion of the heap dedicated to the young generation.  The bigger the young generation, the less often minor collections occur.  However, for a bounded heap size a larger young generation implies a smaller old generation, which will increase the frequency of major collections.  The optimal choice depends on the lifetime distribution of the application.

By default, the young generation size is controlled by NewRatio.  For example, setting -XX:NewRatio=3 means that the ratio between the young and old generation is 1:3; in other words, the combined size of eden and the survivor spaces will be one fourth of the heap.

The parameters NewSize and MaxNewSize bound the young generation size below and above.  Setting these equal to one another fixes the young generation, just as setting -Xms and -Xmx equal fixes the total heap size.  This is useful for tuning the young generation at a finer granularity than the integral multiples allowed by NewRatio

Because the young generation uses copying collection, enough free memory must be reserved in the old generation to ensure that a minor collection can complete.  In the worst case, this reserved memory is equal to the size of eden plus the objects in non-empty survivor space.  When there isn't enough memory available in the old generation for this worst case, a major collection will occur instead.  This policy is fine for small applications, because the memory reserved in the old generation is typically only virtually committed but not actually used.  But for applications needing the largest possible heap, an eden bigger than half the virtually committed size of the heap is useless: only major collections would occur.

If desired, the parameter SurvivorRatio can be used to tune the size of the survivor spaces, but this is often not as important to performance.  For example, -XX:SurvivorRatio=6 sets the ratio between each survivor space and eden to be 1:6; in other words, each survivor space will be one eighth of the young generation (not one seventh, because there are two survivor spaces). 

If survivor spaces are too small, copying collection overflows directly into the old generation.  If survivor spaces are too large, they will be uselessly empty.  At each garbage collection the JVM chooses a threshold number of times an object can be copied before it is tenured.  This threshold is chosen to keep the survivors half full.  (For the intrepid, a 1.3.1 option -XX:+PrintTenuringDistribution can be used to show this threshold and the ages of objects in the new generation.  It is also useful for observing the lifetime distribution of an application.)

Here are the default values for the Solaris (SPARC Platform Edition) operating environment:

NewRatio 2   (client JVM: 8)
NewSize 2172k
MaxNewSize 32m
SurvivorRatio 25

The rules of thumb for server applications are:

First decide the total amount of memory you can afford to give the JVM.  Then graph your own performance metric against young generation sizes to find the best setting.

Unless you find problems with excessive major collection or pause times, grant plenty of memory to the young generation.  The default MaxNewSize (32MB) is generally too small. 

Increasing the young generation becomes counterproductive at half the total heap or less.

Be sure to increase the young generation as you increase the number of processors, since allocation can be parallelized, but GC is not parallel.

Other considerations

For most applications the permanent generation is not relevant to GC performance.  However, some applications dynamically generate and load many classes.  For instance, some implementations of JSPs do this.  If necessary, the maximum permanent generation size can be increased with MaxPermSize.

Some applications interact with garbage collection by using finalization and weak/soft/phantom references.  These features can create performance artifacts at a Java-programming-language level; an example is relying on finalization to close file descriptors, which makes an external resource (descriptors) dependent on GC promptness.  Relying on GC to manage resources other than memory is almost always a bad idea. 

Another way apps can interact with garbage collection is by invoking GCs explicitly, such as through the System.gc() call. These calls force major collection, and inhibit scalability on large systems.  The performance impact of explicit GCs can be measured using the unsupported flag -XX:+DisableExplicitGC.

One of the most commonly encountered uses of explicit GC occurs with RMI's distributed garbage collection (DGC).  Applications using RMI refer to objects in other JVMs.  Garbage can't be collected in these distributed applications without occasional local collection, so RMI forces periodic full collection.  The frequency of these collections can be controlled with properties.  For example,
  java -Dsun.rmi.dgc.client.gcInterval=3600000
       -Dsun.rmi.dgc.server.gcInterval=3600000 ...

specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed.  These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
The Solaris 8 operating environment supports an alternate version of libthread that binds threads to LWPs directly; this may help avoid starvation of the finalization thread.  To try this, set the environment variable LD_LIBRARY_PATH to include /usr/lib/lwp before launching the JVM.

Soft references are cleared less aggressively in the server JVM than the client.  The rate of clearing can be slowed by increasing a parameter in this way: -XX:SoftRefLRUPolicyMSPerMB=10000. The default is value 1000, or one second per megabyte.

For large dedicated systems, there are other special options available to boost performance.

Conclusion

Garbage collection can become a bottleneck in highly parallel systems.  By understanding how GC works, it is possible to use a variety of command line options to minimize that impact.

The demands of large servers are being met with larger hardware configurations that ever before.  For these systems, the 1.4 line of JVMs will provide additional solutions, including a 64 bit address space for even larger generations and concurrent collection to hide the pauses associated with major collection. 
As used on the web site, the terms "Java Virtual Machine and "JVM" mean a virtual machine for the Java platform.

Sunday, April 3, 2011

APTITUDE 28 IFLEX




1)      If the word CAPTAIN is coded like NCNVYKC then what is the code for OBSCURE?

2)      1 7 8 9 6 4 5 6 3 2 7 3 92 99 4 66 36 33 5 664 737 20.
How many even numbers are immediately following another even number?

3)       How many even nos. are immediately followed by 2 even nos.?

4)      The square of a two digit number is divided by half the number, and 36 are added to the quotient. The sum is then divided by 2. The digits of the resulting number are the same as the number, but in reverse order. The digits in the tens place of the original number is twice the difference between the digits. Which of the following could be the number?
a.64     b.36     c. 46    d. None of these
5)      One person says ‘his only daughter is my son’s mother ’, what is the relationship between 1st &2nd person.
  a.   Son
  b.   Daughter
  c.   Son-in-Law
  d.   None of the above
6)      Alphabet ‘A’ to ‘Z’. If we arrange in reverse order (Z to A)then which letter will be in the 5th position towards right ,taken from 11th better from left.
  a.    A
  b.    V
  c.    F
  d.    K
7)       'P’ is product cost; Q is sale price. Express profit .
  a.    { (Q-P)/P}*100
  b.    { (Q-P)/Q}*100
  c.    { (P-Q)/P}*100
  d.    None Of The Above
8)       1,8,27,64,125,?
  a.    234
  b.    216
  c.    450
  d.    None Of the Above


9)       3,5,7,13,11,21,15,?
  a.    19
  b.    28
  c.    29
  d.    31
10)   1,2,3,6,5,10,?
  a.    9
  b.    7
  c.    6
  d.    5
11)   23% of a number is 230 what will be 4/23 th of the numbers
  a.    4000/23
  b.    4000/27
  c.    3000/23
  d.    None Of The Above
12)   A person buys 6, 1 Rs stamps and 7, 50 paisa stamps he has given 12 Rs how much he will get back.
  a.    3 Rs
  b.    4.4 Rs
  c.    2.5 Rs
  d.    None Of The Above
13)   A man is running around a rectangle it takes time 2 time in travelling lenth than travelling width. Total perimeter = 300m
find area
  a.    6000m
  b.    5000m
  c.    3000m
  d.    None Of The Above
14)  Rain:patter
a.       door:bang
b.      birds:flight
c.       animal:graze
d.      men:walk
15)  ABD,DGK,HMS,MTB,SBL,?
a.       ZKW
b.      ZKU
c.       ZAB
d.      XKW
16)  Square root(x)/3 = 243/x value of x ?
17)   If + sign is represented as /, - as *(into,not power do not confuse) , * as - and / as + then what will be the value of (480+20*20)-16 /12 ???
18)  Which of the following will come next in the series IAR, GET , EIV , COX
19)   B is in DOUBT in the same way H is in choices.... HOPE , HOUSE , HONEST , INHIBIT
20)   P+Q represents P is the sister of Q, P-Q represents P is the father of Q and P*Q represents P is the brother  of Q then which will represent K is the aunt of N
21)  In a class puspa ranks 8th from top and 28th from bottom.how many students are there in the class?????
22)  Sum of a number and its one third = 60, 4/5th of the number is ?????
23)   In a rectangle length = twice that of breadth , cost of grounding is 60 rupees per meter,total cost is 3600/- what is the length in meter????????
24)   Qn on sequences which will come next?? 11 13 17 23 31 ? 53 67

APTITUDE Satyam I




1)      A and B can do a piece of work in 20 days. B and C can do it in 12 days. C and A can do it in 10 days. In how much time will A alone would take to do the work
2)      Sum in S.I. becomes 5 times its principal in 8 years what is the rate?
.
3)                                              ?
                               145         161
                         63          71              79
                25            29          33              37
          8           10            12             14            16
     1         2             3              4                5              6
 

4)      What is the right output?
A1 int R=1
A2 K=3
A3 R=R*K*R
A4 PRINT"R"
A5 if(R,=3)
A6 GOTO a3
A7 printf(R8K8K)
A8 Halt

5)      Find the ODD man out
975
867
329
498
none of these

6)      A Can do a piece of work in 18 days . B can do that work in 30 days. Then in how many days they will do twice of that work together?

7)      If 4 NOV 1971 falls on FRIDAY then what is 4 NOV 1869?

8)                              ?
                  92  92
            42    38    42
      18     14    14    18
 6        4      2      4       6
9)      I5 men work for 8 hours a day and it take 9 days for them to complete a work, then how many men had to work for completing the same work ,who work for 7 hours a day and for 12 days?
10) 
                        147
                  75         66
             37       ?        28
      15      16         10     12 
11)  12 man can complete a work in 12 days. For a work 10 men work for 6 days and then 4 more men join them. In how many days will they complete the work?

12)  A man is having some money deposited in bank. In the 1st yr he gets   8% interest, 2nd yr -11 %, 3rd year- 13%. If he gets Rs 12,400 at the end of three yrs. How much had he deposited?

13)  A man took Rs 1000 as loan on simple intrest of 5%. But he pays Rs 200 annually as interest and amount. How much he will have to return  after three years?

14)  7,14,21,9,18,?,11,22,33 

15)  There is a field inside that there is a rectangular grass field with dimension 12X8 meter. One cow is tied at one corner of the grass field with a rope of 10 m. Cow is not allowed to enter the grass field .How much area it will graze?

16)  1 can be written as # and 0 can be written as %....for example
1 is written as #
2 is written as #%
3 is written as ##
4 is written as #%%
then what is the LCM of 20,30,36 ?

17)  A sells an article to B at 10% profit. B sells it to C at 25% profit. C sells it to D at 15% profit. What price did A pay to buy that article if D pays Rs.2056?

18)  If a train of length 150m crosses a man in 12secs then what time it will take to cross a bridge of 250m length

19)  A person always buys rice for Rs 200/- .if price get increased by 10%, then he will take 2 kg less.   Then calculate the increased price of rice

20)  if 14th January 2004 is on Thursday then what was the day of 14th January 1912

21)  A salary + B salary=10000, if A spends 70% of his income, and B spends 80% of his income, the difference  between  the spent money is 500, then what is the salary of A.

22)  The radius of a circle was increased in length by some value. If the increase in circumference is 44 cm, the change in radius is

23)  If $=’0’ and @=’1’And if we can write 0=$                                   
1=@
2=@$
3=@@
4=@$$
Then find out average of @@@@ and @@@$$@
      
24)  For a given set of numbers as 32, 45, 57, 142, 180, A machine gives following outputs after each step as shown below:
    Step 1  33,47,60,146,185
    step 2  33,185,60,146,47
    step 3  34,185,63,146,52
    step 4  52,34,63,146,185
    step 5  185,146,63,34,52
If you are given a set of numbers as 7,5,3,9,13, What is the output of machine after step 5 ?

APTITUDE Satyam II




1)      If a boat goes upstream with a speed of U km/h and downstream with a speed V km/h, what will be speed of boat in still water?

2)      If a clock loses 27% time in first seven days and gains 31% in next seven days, what will be the correct time exactly after two weeks if clock was initially set to 12 noon

3)      Pyramid series
            127
         65   56
      33   ?    24
   15  16  10   12

4)      Find the angle b/w the hands at 14:42 hours?

5)      What are the no. of words that can be formed from 'COOLER' such that both the Os are not together.

6)      if a boy goes at 15kmph and returns back at 20kmph what is his average speed

7)      When a dies and coin are tossed what is the probability of getting head and 6 on top.

8)      Find the missing number 2, 4, 6, 5,?, 9, 8, 10, 12

9)      A person purchases two items at same price. He sell one at 20% loss, Then at what price he has to sell the second item so as not to have no profit no loss.

10)  Find the missing Number? 40,50,60, ? ,66,78, 42,56,70

11)  Father is 30 years older than his son After 5 years father’s age will be thrice the son's age, then what is the fathers age?

12)  Particular distance is covered in 42 min. But 2/3 rd of that distance is covered at 4 kmph and the remaining is covered at 5 kmph. Then what is the total distance covered?

13)  A,B,C,D,E  and F are books, in that  Blue, Red and Old , New Books are there. The Books B,C and E are in Blue color and D,F are New Books and A,C and D are Law books , and B,E and F are gazette. Then which is Old Gazette Book?

14)  If A is coded as B, B is coded as C, C is coded as D, and so on... Then What will "INDONESIA"

15)  P,Q,R,S,T and U are the six people sitting in a circle. P is sitting left of U and right of  S. Q is sitting direct opposite to P, and right of T. If P and R are inter changed then who will be sitting near S?

16)  A shopkeeper marks the product 25% above the cost price and he allows 12 % discount.  What percentage profit will he get?

17)  If + is considered as *,  - is considered as  /, * is considered as + and / is considered as  - then simplify the following? 300-5+(15*7)

18)  The distance between two stations A and B is 220km, a train from B station starts towards the station A at a speed of 80kmph and another train starts from half-an hour later towards the same station A at a speed of 100kmph. At what distance the both will meet each other

19)  A man buys two article ,the price of the second one is 4/5 the of the first then he sells the first one at 12.5 % gain and the second one at 10% loss .Find loss or gain and by how much?

20)  The length of the circumference of a circle is equal to the perimter of triangle of equal sides and perimeter of square. the area of circle, triangle and square is c,t and s respectively.then
 a)c>s>t  b)t>s>c  c)c>t>s d)none

21)  A container contains 12 ltr of water. Some water is drained from it such that water in the container is 6 lts more than the drained water. Amount of water drained is?

22)  An alloy of copper and tin are in the ratio 8:3, another alloy of the same are in the ratio 6:5.Equal weights of these two alloys are combined and formed a third alloy C. What is the ratio of copper and tin in C?

23)  A man deposited a total of 25000 Rs in a bank some amount at the rate15%  annum rest and some amount for18% annum rest. After an year he got a Rs4050 as interest. Find amount he spent for 18/annum.

24)  P&Q are 2 points 22km apart. A&B are walking from P to Q at 5 & 6km/hr respectively. B reaches Q and returns to P, and meets A at a point R. Find the distance from P to R