Showing posts with label java changes. Show all posts
Showing posts with label java changes. Show all posts

Friday 30 August 2013

Top Most Java Memory Management

We are covering here -'Java garbage collection interview questions' or 'Java memory interview questions' in details. The topic is always asked to senior java developers to verify the java memory model understanding. In bigger project taking care of VM memory becomes very important due to more memory required at peak time processing in application.  

In this topic frequently asked questions are:

  • What is Garbage collection?
  • How to do analysis of java memory issues?
  • Explain Java memory model?
  • What are garbage collectors?
  • How to use java profilers?
  • Have you worked in application performance improvement?
  • What are the memory issues you have faced in your application?

Garbage Collection:


Garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.

Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system. However, many systems use a combination of approaches, including other techniques such as stack allocation and region inference.

Resources other than memory, such as network sockets, database handles, user interaction windows, and file and device descriptors, are not typically handled by garbage collection. Methods used to manage such resources, particularly destructors, may suffice to manage memory as well, leaving no need for GC. Some GC systems allow such other resources to be associated with a region of memory that, when collected, causes the other resource to be reclaimed; this is called finalization. Finalization may introduce complications limiting its usability, such as intolerable latency between disuse and reclaim of especially limited resources, or a lack of control over which thread performs the work of reclaiming.

Memory is divided in mainly 3 areas:
  •  Young\Eden Generation : for newly created objects.
  •  Tenured Generation : for old objects which are survived after minor gc.
  •  Perm Space : for class definition, meta data and string pools.



At initialization, a maximum address space is virtually reserved but not allocated to physical memory unless it is needed. The complete address space reserved for object memory can be divided into the young and tenured generations.The young generation consists of eden and two survivor spaces. Most objects are initially allocated in eden. One survivor space is empty at any time, and serves as the destination of any live objects in eden and the other survivor space during the next copying collection. Objects are copied between survivor spaces in this way until they are old enough to be tenured (copied to the tenured generation). A third generation closely related to the tenured generation is the permanent generation which holds data needed by the virtual machine to describe objects that do not have an equivalence at the Java language level.

Java objects are created in Heap and Heap is divided into three parts or generations of garbage collection in Java as mentioned above. New Generation is divided into three parts known as 
  •   Eden space
  •   Survivor 1 
  •   Survivor 2 space. 
When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is special and it is used to stores String pool,  Meta data related to classes and method in JVM.

Out Of Memory / OOM :
   If it happens in your application take it is opportunity to display your technical skills. In technical term it means the JVM does not have space to put objects in tenured space which are survived in minor collection and it stops working or responding due to no memory to do further processing.
 
These are terms used in context of java memory management:

  • 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 occurring.
  • 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 remote method invocation (RMI).
  • Heap Dump is a list of objects in the memory of JVM as well as the content of the memory occupied by those objects. It preserves the value of any attributes of the objects, including references to other objects. In other words, a heap dump gives you a complete picture of the memory.There are multiple tools that allow you to dump heap in a Java process:Some tools like VisualVM and memory profilers allow you to initiate a heap dump from the GUI, but you don’t need any fancy tools here—jmap will do just fine. As it provides the most general case, we'll use jmap in the next example.Before you dump heap, be sure to keep the following issues in mind:Note that the -F option, which will dump non-responsive programs, might be useful on UNIX systems, but is not available on Windows. Note also that JDK 6 includes the option +XX:+HeapDumpOnOutOfMemoryError that will dump heap whenever the OutOfMemoryError alert is encountered. This can be a useful option, but keep in mind that it has the potential to consume significant amounts of disk space.


The basic principles of garbage collection are:

  1. Find data objects in a program that cannot be accessed in the future
  2. Reclaim the resources used by those objects



   An object is considered 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 considered garbage. The time this approach takes is proportional to the number of live objects, which is prohibitive for large applications maintaining lots of live data.The blue area in the diagram below is a typical distribution for the lifetimes of objects. The X axis is object lifetimes measured in bytes allocated. The byte count on the Y axis is the total bytes in objects with the corresponding lifetime. The sharp peak at the left represents objects that can be reclaimed (i.e., have "died") shortly after being allocated. Iterator objects, for example, are often alive for the duration of a single loop.   


Application GC bytes allocation is shown in above picture. Majority of byte survival happens in Minor Collection and majority of objects are cleared in Major collections. Some objects do live longer, and so the distribution stretches out to the the right. For instance, there are typically some objects allocated at initialisation 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 initial 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".



Collectors

The Java HotSpot VM includes three different collectors, each with different performance characteristics.
  • The serial collector uses a single thread to perform all garbage collection work, which makes it relatively efficient since there is no communication overhead between threads. It is best-suited to single processor machines, since it cannot take advantage of multiprocessor hardware, although it can be useful on multiprocessors for applications with small data sets (up to approximately 100MB). The serial collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseSerialGC.
  • The parallel collector (also known as the throughput collector) performs minor collections in parallel, which can significantly reduce garbage collection overhead. It is intended for applications with medium- to large-sized data sets that are run on multiprocessor or multi-threaded hardware. The parallel collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseParallelGC.
  • Newparallel compaction is a feature introduced in J2SE 5.0 update 6 and enhanced in Java SE 6 that allows the parallel collector to perform major collections in parallel. Without parallel compaction, major collections are performed using a single thread, which can significantly limit scalability. Parallel compaction is enabled by adding the option -XX:+UseParallelOldGC to the command line.
  • The concurrent collector performs most of its work concurrently (i.e., while the application is still running) to keep garbage collection pauses short. It is designed for applications with medium- to large-sized data sets for which response time is more important than overall throughput, since the techniques used to minimize pauses can reduce application performance. The concurrent collector is enabled with the option -XX:+UseConcMarkSweepGC.

    VM Options for GC details:

    • -verbose:gc — prints basic information about GC to the standard output
    • -XX:+PrintGCTimeStamps — prints the times that GC executes
    • -XX:+PrintGCDetails — prints statistics about different regions of memory in the JVM
    • -Xloggc: — logs the results of GC in the given file.


      These Command line options are available via JMX to monitor VM memory-
      • -Dcom.sun.management.jmxremote — enables JMX monitoring
      • -Dcom.sun.management.jmxremote.port = — controls the port for JMX monitoring
      • com.sun.management.jmxremote.ssl
      • com.sun.management.jmxremote.authenticate
      • If you're using JDK 6, you can use tool called jmap on any platform.

        What is Garbage First Collector?

         Recently in one java interview, I was asked about Garbage First collector and Garbage First collector splits the heap up into fixed-size regions and tracks the live data in those regions. It keeps a set of pointers — the "remembered set" — into and out of the region. When a GC is deemed necessary, it collects the regions with less live data first (hence, "garbage first"). Often, this can mean collecting an entire region in one step: if the number of pointers into a region is zero, then it doesn't need to do a mark or sweep of that region.
            For each region, it tracks various metrics that describe how long it will take to collect them. You can give it a soft real-time constraint about pause times, and it then tries to collect as much garbage as it can in that constrained time.

        Technical description

        The G1 collector achieves high performance and pause time goals through several techniques.
        The heap is partitioned into a set of equal-sized heap regions, each a contiguous range of virtual memory. G1 performs a concurrent global marking phase to determine the liveness of objects throughout the heap. After the mark phase completes, G1 knows which regions are mostly empty. It collects in these regions first, which usually yields a large amount of free space. This is why this method of garbage collection is called Garbage-First. As the name suggests, G1 concentrates its collection and compaction activity on the areas of the heap that are likely to be full of reclaimable objects, that is, garbage. G1 uses a pause prediction model to meet a user-defined pause time target and selects the number of regions to collect based on the specified pause time target.
        The regions identified by G1 as ripe for reclamation are garbage collected using evacuation. G1 copies objects from one or more regions of the heap to a single region on the heap, and in the process both compacts and frees up memory. This evacuation is performed in parallel on multi-processors, to decrease pause times and increase throughput. Thus, with each garbage collection, G1 continuously works to reduce fragmentation, working within the user defined pause times. This is beyond the capability of both the previous methods. CMS (Concurrent Mark Sweep ) garbage collection does not do compaction. ParallelOld garbage collection performs only whole-heap compaction, which results in considerable pause times.
        It is important to note that G1 is not a real-time collector. It meets the set pause time target with high probability but not absolute certainty. Based on data from previous collections, G1 does an estimate of how many regions can be collected within the user specified target time. Thus, the collector has a reasonably accurate model of the cost of collecting the regions, and it uses this model to determine which and how many regions to collect while staying within the pause time target.

        Recommended Use Cases for G1

        The first focus of G1 is to provide a solution for users running applications that require large heaps with limited GC latency. This means heap sizes of around 6GB or larger, and stable and predictable pause time below 0.5 seconds.
        Applications running today with either the CMS or the ParallelOld garbage collector would benefit switching to G1 if the application has one or more of the following traits.
        • More than 50% of the Java heap is occupied with live data.
        • The rate of object allocation rate or promotion varies significantly.
        • Undesired long garbage collection or compaction pauses (longer than 0.5 to 1 second)

          Thursday 29 August 2013

          Top Most Java 1.7 features



          'Java latest changes' or' 'Java 1.7 changes' are covered in this topic. Java 1.7 [ Dolphin] is major update after java 1.5 tiger release. It is done on 2011-07-28 after around 5 years of java release 1.6 [Mustang]. These are major changes in java 1.7 release and most important is definitely 'Auto closeable' of resources.

          1) Autocloseable Try Statement defining Resources – Java 1.7 introduces all new try-with-resources statement using which declaration and initialization of one or more resources can happen. But only the resources that implement the interface “java.lang.AutoCloseable” can be declared. Example:
                try (BufferedReader bufferedReader = new BufferedReader( FileReader(path)))
                   {             return bufferedReader.readLine();  
                   }
            In this code snippet, sampleBufferedReader instance is created within the try statement. Note that the example does not include a finally block that contains a code to close sampleBufferedReader as in Java 1.6 or earlier versions. Java 1.7 automatically closes the resources that are instantiated within the try-with-resources statement as shown above.

          2) Catch Block Handling Multiple Exceptions – In Java 1.5 and Java 1.6, a catch block can handle only one type of exception. But in Java 1.7 and later versions, a single catch block can handle multiple exceptions. Here is an example showing catch blocks in Java 1.6:
               try {    }
                catch(SQLException exp1)
                {     throw exp1;    }
                 catch(IOException exp2)
                 {    throw exp2;   }
          The same code snippet can be modified in Java 1.7 as:
                try  {….      }
                catch(SQLException | IOException |ArrayIndexOutofBoundsException exp1)
                {     throw exp1;   }

          3) String Object as Expression in Switch Statement – So far only integral types are used as expressions in switch statement. But Java 1.7 permits usage of String object as a valid expression. Example:
             example:           
                                      case "CASE1":
                                               System.out.println(“CASE1”);
                                               break;

          4) JDBC in Java 1.7
          JDBC contained in Java 1.7 / Java SE 7 is JDBC 4.1 that is newly getting introduced. JDBC 4.1 is more efficient when compared to JDBC 4.0.

          5) Language Enhancements in JDBC 1.7
          Java 1.7 introduces many language enhancements:

            Integral Types as Binary Literals – In Java 1.7 / Java SE 7, the integral types namely byte, short, int and long can also be expressed with the binary number system. To specify these integral types as binary literals, add the prefix 0B or 0b to number. For example, here is a byte literal represented as 8-bit binary number:
               byte sampleByte = (byte)0b01001101;
             
            Underscores Between Digits in Numeric Literal – In Java 1.7 and all later versions, “_” can be used in-between digits in any numeric literal. “_” can be used to group the digits similar to what “,” does when a bigger number is specified. But “_” can be specified only between digits and not in the beginning or end of the number. Example:
          long NUMBER = 444_67_3459L;
          In this example, the switch expression contains a string called sampleString.  The value of this string is matched with every case label and when the string content matches with case label then the corresponding case gets executed. 

            Automatic Type Inference during the Generic Instance Creation – In Java 1.7 while creating a generic instance, empty parameters namely <> can be specified instead of specifying the exact type arguments. However, this is permitted only in cases where the compiler can infer the appropriate type arguments. For example, in Java 1.7 you can specify:
                sampleMap = new HashMap<>();
          Thus HashMap<> can be specified instead of HashMap>;. This <>; empty parameters of Java 1.7 are named as diamond operator.

          6) Suppress Warnings - When declaring varargs method that includes parameterized types, if the body of the varargs method does not throw any exceptions like ClassCastException (which occurs due to improper handling of the varargs formal parameter) then the warnings can be suppressed in Java 1.7 by three different ways: 
          (1) Add annotation @SafeVarargs to static method declarations and non constructor method declarations 
          (2) Add annotation @SuppressWarnings({"unchecked", "varargs"}) to varargs method declaration 
          (3) Directly use compiler option “-Xlint:varargs.
          By suppressing the warnings in varargs method, occurrence of unchecked warnings can be prevented at compile time thus preventing Heap Pollution.

          7) Java Virtual Machine Enhancements in Java 1.7
          Java SE 7 / Java 1.7 newly introduce a JVM instruction called “invokedynamic” instruction.  Using “invokedynamic” instruction, the dynamic types programming language implementation becomes simpler. Thus Java 1.7 enables JVM support for the non-java languages.  


          Sunday 4 August 2013

          Top Most JAVA 1.5 features | update Java 7 features


          This Blog covers these topics: Java 1.5 interview questions / Java 1.5 updates / Java 1.7 updates. These are main changes in java 1.5 [ Tiger Release ] and these details are taken from SUN publication on jdk 1.5.

          JAVA 1.5 New Features:
          In Summary:
          1) Generics
          2) Enhanced For Loop
          3) Autoboxing / Unboxing
          4) Enums
          5) Varags
          6) Static Import
          7) Metadata / Annotations
          8) Garbage Collectors
          9) Java Concurrent package

          Worth reading java 1.7 changes to confirm that you are up-to-date for java changes.
          Details of each change in java 1.5-
          Generics
          This long-awaited enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting. Refer to JSR 14.
                Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.
          Example
          static void expurgate(Collection; c) {
              for (Iterator; i = c.iterator(); i.hasNext(); )
                if (i.next().length() == 4)
                  i.remove();
          }
            The java.util.Collections class has been outfitted with wrapper classes that provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers. These “checked collection wrappers” are very useful for debugging. Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:
              Set s = new HashSet();

          Enhanced for Loop
          This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays. Refer to JSR 201 .
             Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and cancels them:
          void cancelAll(Collection; c) {
              for (Iterator; i = c.iterator(); i.hasNext(); )
                  i.next().cancel();
                 }
             The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:
          void cancelAll(Collection ; c) {
              for (TimerTask t : c)
                  t.cancel();
            }
            When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.

          Autoboxing/Unboxing
          This facility eliminates the drudgery of manual conversion between primitive types (such as int) and wrapper types (such as Integer). Refer to JSR 201 .
             As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
             The following example illustrates autoboxing and unboxing, along with generics and the for-each loop. In a mere ten lines of code, it computes and prints an alphabetized frequency table of the words appearing on the command line.
           import java.util.*;
          // Prints a frequency table of the words on the command line
          public class Frequency {
             public static void main(String[] args) {
                Map m = new TreeMap();
                for (String word : args) {
                    Integer freq = m.get(word);
                    m.put(word, (freq == null ? 1 : freq + 1));
                }
                System.out.println(m);
            }
          }
          java Frequency if it is to be it is up to me to do the watusi
          {be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}

          Typesafe Enums
             This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern ("Effective Java," Item 21) without the verbosity and the error-proneness. Refer to JSR 201.
          In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
          // int Enum Pattern - has severe problems!
          public static final int SEASON_WINTER = 0;
          public static final int SEASON_SPRING = 1;
          public static final int SEASON_SUMMER = 2;
          public static final int SEASON_FALL   = 3;
          This pattern has many problems, such as:
          • Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
          • No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
          • Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
          • Printed values are uninformative - Because they are just ints, if you print one out all      you get is a number, which tells you nothing about what it represents, or even what type it is.
               It is possible to get around these problems by using the Typesafe Enum pattern (see Effective Java Item 21), but this pattern has its own problems: It is quite verbose, hence error prone, and its enum constants cannot be used in switch statements.
              In 5.0, the Java™ programming language gets linguistic support for enumerated types. In their simplest form, these enums look just like their C, C++, and C# counterparts:
                enum Season { WINTER, SPRING, SUMMER, FALL }
           All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else. The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

          Varargs
            This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists. Refer to JSR 201.
             In past releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:
          Object[] arguments = {
              new Integer(7),
              new Date(),
              "a disturbance in the Force"
          };
          String result = MessageFormat.format(
              "At {1,time} on {1,date}, there was {2} on planet "
               + "{0,number,integer}.", arguments);
             It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:
              public static String format(String pattern, Object... arguments);

          Static Import
            This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern." Refer to JSR 201.
            In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:
                   double r = Math.cos(Math.PI * theta);
            In order to get around this, people sometimes put static members into an interface and inherit from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it: the Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class's use of the static members of another class is a mere implementation detail. When a class implements an interface, it becomes part of the class's public API. Implementation details should not leak into public APIs.
                    The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:
          import static java.lang.Math.PI;
          or en masse:
          import static java.lang.Math.*;
          Once the static members have been imported, they may be used without qualification:
          double r = cos(PI * theta);

          Metadata (Annotations)
          Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.
          Annotations have a number of uses, among them:
          • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
          • Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
          • Runtime processing — Some annotations are available to be examined at runtime.
          Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.
          The annotation appears first, often (by convention) on its own line, and may include elements with named or unnamed values:
          @Author(
             name = "Benjamin Franklin",
             date = "3/27/2003"
          )
          class MyClass() { }
          or
          @SuppressWarnings(value = "unchecked")
          void myMethod() { }
          There are three annotation types that are predefined by the language specification itself: @Deprecated@Override, and @SuppressWarnings[example - @SuppressWarnings("deprecation")].

          Annotation Processing
          The more advanced uses of annotations include writing an annotation processor that can read a Java program and take actions based on its annotations. It might, for example, generate auxiliary source code, relieving the programmer of having to create boilerplate code that always follows predictable patterns. To facilitate this task, release 5.0 of the JDK includes an annotation processing tool, called apt. In release 6 of the JDK, the functionality of apt is a standard part of the Java compiler.
          To make annotation information available at runtime, the annotation type itself must be annotated with @Retention(RetentionPolicy.RUNTIME), as follows:
          import java.lang.annotation.*; 
          @Retention(RetentionPolicy.RUNTIME)
          @interface AnnotationForRuntime {
             // Elements that give information
             // for runtime processing
          }

          Virtual Machine
          Class Data Sharing
            The class data sharing feature is aimed at reducing application startup time and footprint. The installation process loads a set of classes from the system jar file into a private, internal representation, then dumps that representation to a "shared archive" file. During subsequent JVM invocations, the shared archive is memory-mapped in, saving the cost of loading those classes and allowing much of the JVM's metadata for these classes to be shared among multiple JVM processes. For more information, click the above link.
             Class data sharing (CDS) is a new feature in J2SE 5.0 intended to reduce the startup time for Java programming language applications, in particular smaller applications, as well as reduce footprint. When the JRE is installed on 32-bit platforms using the Sun provided installer, the installer loads a set of classes from the system jar file into a private internal representation, and dumps that representation to a file, called a "shared archive". Class data sharing is not supported in Microsoft Windows 95/98/ME. If the Sun JRE installer is not being used, this can be done manually, as explained below. During subsequent JVM invocations, the shared archive is memory-mapped in, saving the cost of loading those classes and allowing much of the JVM's metadata for these classes to be shared among multiple JVM processes.
             In J2SE 5.0, class data sharing is supported only with the Java HotSpot Client VM, and only with the  serial garbage collector.
          The primary motivation for including CDS in the 5.0 release is the decrease in startup time it provides. CDS produces better results for smaller applications because it eliminates a fixed cost: that of loading certain core classes. The smaller the application relative to the number of core classes it uses, the larger the saved fraction of startup time.
           The footprint cost of new JVM instances has been reduced in two ways. First, a portion of the shared archive, currently between five and six megabytes, is mapped read-only and therefore shared among multiple JVM processes. Previously this data was replicated in each JVM instance. Second, since the shared archive contains class data in the form in which the Java Hotspot VM uses it, the memory which would otherwise be required to access the original class information in rt.jar is not needed. These savings allow more applications to be run concurrently on the same machine. On Microsoft Windows, the footprint of a process, as measured by various tools, may appear to increase, because a larger number of pages are being mapped in to the process' address space. This is offset by the reduction in the amount of memory (inside Microsoft Windows) which is needed to hold portions on rt.jar. Reducing footprint remains a high priority.


          Garbage Collector Ergonomics
          The parallel collector has been enhanced to monitor and adapt to the memory needs of the application. You can specify performance goals for applications and the JVM will tune the size of the Java heap to meet those performance goals with the smallest application footprint consistent with those goals. The goal of this adaptive policy is to eliminate the need to tune command-line options to achieve the best performance. For a synopsis of garbage collection features, click the above link.

          The following changes take effect with J2SE 5.0.
          on server-class machines running the server VM, the garbage collector (GC) has changed from the previous serial collector (-XX:+UseSerialGC) to a parallel collector (-XX:+UseParallelGC). You can override this default by using the -XX:+UseSerialGC command-line option to the java command.
          1. On server-class machines running either VM (client or server) with the parallel garbage collector (-XX:+UseParallelGC) the initial heap size and maximum heap size have changed as follows.
          initial heap size:
          Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.
          maximum heap size:
          Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.

          Server-Class Machine Detection
          At application startup, the launcher can attempt to detect whether the application is running on a "server-class" machine.
          Starting with J2SE 5.0, when an application starts up, the launcher can attempt to detect whether the application is running on a "server-class" machine and, if so, use the Java HotSpot Server Virtual Machine (server VM) instead of the Java HotSpot Client Virtual Machine (client VM). The aim is to improve performance even if no one configures the VM to reflect the application it's running. In general, the server VM starts up more slowly than the client VM, but over time runs more quickly.
          Note: For J2SE 5.0, the definition of a server-class machine is one with at least 2 CPUs and at least 2GB of physical memory.
          In J2SE 5.0, server-class detection occurs if neither -server nor -client is specified when launching the application on an i586 or Sparc 32-bit machine running Solaris or Linux. As the following table shows, the i586 Microsoft Windows platform is not subject to the server-class test (i.e., is never treated as a server-class machine by default) and uses the client VM by default. The remaining Sun-supported platforms use only the server VM.
          J2SE Development Kit 5.0 has several enhancments in the java.lang.* and java.util.* packages, including:
          ·         ProcessBuilder - The new ProcessBuilder class provides a more convenient way to invoke subprocesses than does Runtime.exec. In particular, ProcessBuilder makes it easy to start a subprocess with a modified process environment (that is, one based on the parent's process environment, but with a few changes).
          ·         Formatter - An interpreter for printf-style format strings, the Formatter class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as byte, java.math.BigDecimal , and java.util.Calendar are supported. Limited formatting customization for arbitrary user types is provided through the java.util.Formattable interface.
          ·         Scanner - The java.util.Scanner class can be used to convert text into primitives or Strings. Since it is based on the java.util.regex package, it also offers a way to conduct regular expression based searches on streams, file data, strings, or implementors of the Readable interface.
          ·         Concurrency Utilities The java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks packages provide a extensible framework of high-performance, scalable, thread-safe building blocks for developing concurrent classes and applications, including thread pools, thread-safe collections, semaphores, a task scheduling framework, task synchronization utilities, atomic variables, and locks. Additionally, these packages provide low-level primitives for advanced concurrent programming which take advantage of concurrency support provided by the processor, enabling you to implement high-performance, highly scalable concurrent algorithms in Java to a degree not previously possible without using native code. For more information, refer to JSR 166 .
          ·         Collections Framework Enhancements - There are many enhancements to the Collections framework.
          ·         Instrumentation - The new java.lang.instrument package provides services that allow Java programming agents to instrument programs running on the Java virtual machine by modifying methods' bytecodes at runtime.
          ·         Threads - The java.lang.Thread class has the following enhancements:

          o    Thread priority handling has changed.
          o    Thread.State enum class and the new getState() API are provided for querying the execution state of a thread.
          o    The new thread dump API - the getStackTrace and getAllStackTraces methods in the Thread class - provides a programmatic way to obtain the stack trace of a thread or all threads.
          o    The uncaughtExceptionHandler mechanism, previously available only through the ThreadGroup class, is now available directly through the Thread class.
          o    A new form of the sleep() method is provided which allows for sleep times smaller than one millisecond.

          Scanner
          The java.util.Scanner class can be used to convert text into primitives or Strings. Since it is based on the java.util.regex package, it also offers a way to conduct regular expression based searches on streams, file data, strings, or implementors of the Readable interface. A simple text scanner which can parse primitive types and strings using regular expressions.
          A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.  For example, this code allows a user to read a number from System.in:
               Scanner sc = new Scanner(System.in);
               int i = sc.nextInt();

          Concurrency Utilities
          The java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks packages provide a powerful, extensible framework of high-performance, scalable, thread-safe building blocks for developing concurrent classes and applications, including thread pools, thread-safe collections, semaphores, a task scheduling framework, task synchronization utilities, atomic variables, and locks. The addition of these packages to the core class library frees the programmer from the need to craft these utilities by hand, in much the same manner that the Collections Framework did for data structures. Additionally, these packages provide low-level primitives for advanced concurrent programming which take advantage of concurrency support provided by the processor, enabling programmers to implement high-performance, highly scalable concurrent algorithms in the Java language to a degree not previously possible without resorting to native code. Refer to JSR 166 .

          Threads
          The java.lang.Thread class has the following enhancements:
                .Thread priority handling has changed; see the above link for details.
                ·  Thread.State enum class and the new getState() API are provided for querying the execution state of a thread.
             · The new thread dump API - the getStackTrace and getAllStackTraces methods in the Thread class - provides a programmatic way to obtain the stack trace of a thread or all threads.
                ·  The uncaughtExceptionHandler mechanism, previously available only through the ThreadGroup class, is now available directly through the Thread class.

          ·         A new form of the sleep() method is provided which allows for sleep times smaller than one millisecond.
          The Concurrency Utilities includes:
          • Task Scheduling Framework - The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Implementations are provided that allow tasks to be executed within the submitting thread, in a single background thread (as with events in Swing), in a newly created thread, or in a thread pool, and developers can create of Executor supporting arbitrary execution policies. The built-in implementations offer configurable policies such as queue length limits and saturation      policy which can improve the stability of applications by preventing runaway resource consumption.
          • Concurrent Collections - Several new Collections classes have been added, including the new Queue and BlockingQueue interfaces, and high-performance, concurrent implementations of Map, List, and Queue.
          • Atomic Variables - Classes for atomically manipulating single variables (primitive types or references), providing high-performance atomic arithmetic and compare-and-set methods. The atomic variable implementations in java.util.concurrent.atomicoffer higher performance than would be available by using synchronization (on most platforms), making them useful for implementing high-performance concurrent algorithms as well as conveniently implementing counters and sequence number generators.
          • Synchronizers - General purpose synchronization classes, including semaphores,mutexes, barriers, latches, and exchangers, which facilitate coordination between threads.
          • Locks - While locking is built into the Java language via the synchronized keyword, there are a number of inconvenient limitations to built-in monitor locks. The java.util.concurrent.locks package provides a high-performance lock implementation with the same memory semantics as synchronization, but which also supports specifying a timeout when attempting to acquire a lock, multiple condition variables per lock, non-lexically scoped locks, and support for interrupting threads which are waiting to acquire a lock.
          • Nanosecond-granularity timing - The System.nanoTime method enables access to a nanosecond-granularity time source for making relative time measurements, and methods which accept timeouts (such as the BlockingQueue.offer, BlockingQueue.poll,Lock.tryLock, Condition.await, and Thread.sleep) can take timeout values in nanoseconds. The actual precision of System.nanoTime is platform-dependent.    



           Java 1.7 changes details like multi Exceptions catch block and Resource auto close able feather. 
          Java 1.7 features      



            LinkWithin

            Related Posts Plugin for WordPress, Blogger...

            Labels

            Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt