Showing posts with label java questions. Show all posts
Showing posts with label java questions. 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.  


          Friday 23 August 2013

          Top Most java interview with Investment bank -3

          This Interview was scheduled on Aug,2011 with one of the BIG 4 US banks. The positions was related to senior java developer and they were looking for strong java candidate with problem solving skills. They had a Rule based java application on which they were facing performance issue. The application was using Hibernate,Spring, Java 1.5 and JMS with Oracle database.

          1'st Round ) It was Quick fire round with 20  minutes telephonic interviews.
          Technical questions:
          1. Benefits of using Hibernate in application? 
          2. How to manage transaction in Hibernate and what all are transaction attributes?
          3. How to avoid phantom read using in Database operations?
          4. What is Queue and Topic and How to manage transaction in JMS?
          5. What is garbage collection?
          6. What need to be taken care on Java performance?
          7. How to do application profiling?
          8. What is database index and what is cluster index?
          9. Difference in Database functions\procedure and trigger?
          2) Second Round tech. interview
          It was second round face to face technical interview and it was totally focused on hibernate. I was not sure why interviewee is just asking questions on Hibernate.
          1. What is cascade all in hibernate setting?
          2. how to maintain same object in two hibernate sessions?
          3. what is Session.merge()?
          4. what is datasource and what is benefits?
          5. what is transaction management?
          6. what is DurableSubscriber?
          7. How to avoid circular dependency?
          8. How to do transaction management ? 
          9. How hashmap get and set works?
          10. How to design the big application where lots of request comes a same time and your application should able to handle all requests? why we should use JMS and what are the other alternative?
          11. diff in runnable and callable?
          12. diff in ArrayBlockingQueue, ConcurrentLinkedQueue?
          13. How the ExecutorService works?
          14. Have you used concurrent hashmap?
          15. How the task are submitted in executor framework?
          16. Java 1.5 concurrency package benefit?
          17.  what is Drul rule engine ?

             My second round went well , except deep questions in hibernate . I was able to give answers but they were not satisfied with my answers on hibernate as last time I worked in hibernate was 2 years before and finally got rejected here.

          Monday 19 August 2013

          Top Most Java Producer and Consumer Implementation using Blocking Queue

          'Java Consumer Producer' example - This is one of frequently asked questions to senior core java developer. Java concurrency producer and consumer solution is demonstrated below. 
          Java Concurrency Queuing options:
           The java concurrent executors and task holding queues can be configured in three ways-
          Direct handoffs :  A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.

          Unbounded queues : Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.

          Bounded queues : A bounded queue (for example, an ArrayBlockingQueue) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may be traded off for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.

             Example of PriorityBlockingQueue and see how the comparable is used with priority of task which depends on implementation of compare method in task.
          From Java Docs-

          The Blocking queue here is bounded with 11 as initial capacity as default constructor.  The queue is based on priority and least priority data is processed 

          " An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError). This class does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).
          This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityBlockingQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). Also, methoddrainTo can be used to remove some or all elements in priority order and place them in another collection."




          Output
           Consumed Data [number=2, name=two]
           producer 0
           Consumed Data [number=10, name=ten]
           producer 1
           Consumed Data [number=20, name=twenty]
           producer 2
           Consumed Data [number=0, name=0]
           producer 3
           Consumed Data [number=1, name=1]
           producer 4
           Consumed Data [number=2, name=2]
           producer 5
           Consumed Data [number=3, name=3]


          Consumer Producer Solution with Synchronisation:
          This implementation with Synchronisation needs great care and it is more complicated in implementation:


          Output 
          The output will confim that there is no concurrency issue on putting data into same queue and wait() and notify() works perfectly fine.
           Got: 53613
           Put: 53614
           Got: 53614
           Put: 53615
           Got: 53615
           Put: 53616
           Got: 53616
           Put: 53617
           Got: 53617

          Sunday 18 August 2013

          Top Most Design Pattern in Java : Part 1

          'Java investment bank interview' generally contains 'Java Design Pattern' questions. If you want to be a professional Java developer, you should know popular solutions for common\standard coding problems. Such solutions have been proved efficient and effective and always used by experienced developers. These solutions are described as so-called design patterns. Learning design patterns speeds up your experience accumulation in OOA/OOD. Once you grasped them, you would be benefit from them for all your life and jump up yourselves to be a master of designing and developing. Furthermore, you will be able to use these terms to communicate with your fellows more effectively.

          Many programmers with many years experience don't know design patterns, but as an Object-Oriented programmer, you have to know them well, especially for new Java programmers. Actually, when you solved a coding problem, you have used a design pattern. 


                  You may not use a popular name to describe it or may not choose an effective way to better intellectually control over what you built. Learning how the experienced developers to solve the coding problems and trying to use them in your project are a best way to earn your experience. We have mainly 3 type of design pattern and they are Creational, Structural and Behavioural.

          There are frequently asked question in design pattern, and these were asked to me in java interviews:

          1) Explain Singleton Design pattern and How to solve Double Check locking?
          2) What is Abstract Factory Pattern?
          3) What is Adapter pattern?
          4) What is Decorator Design Pattern?
          5) Where we should use Facade in application?
          6) What is Proxy and Composite?
          7) What is Observer Pattern? 
          Creational Patterns
          Factory:
          The factory pattern \ factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."[1]
          Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

          The factory pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects. 
          Example : Static factory method provided with Collections class like 
          Collections.synchronizedMap( new HashMap()); 

          Abstract Factory:
          The abstract factory pattern is a software creational design pattern that provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.
          An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() andcreateResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects).

          Example : The best example will be configuring Database connection factory which hide underline Database type. We can configure Oracle, DB2 or Sybase Connection Factory in application.
              > java.util.Calendar#getInstance()
              > java.util.ResourceBundle#getBundle()
              > java.text.NumberFormat#getInstance()

          Singleton:
          The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
          In the second edition of his book Effective JavaJoshua Bloch claims that "a single-element enum type is the best way to implement a singleton" for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
           Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
          The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). More details on Singleton Pattern.
          Example: Getting Runtime environment using Runtime class is example of Singleton design pattern -- java.lang.Runtime#getRuntime()

          Builder:
          The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance with the composite pattern.The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.

          Builder
          Abstract interface for creating objects (product).
          Concrete Builder
               Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.
          Example : Builder pattern is frequently used in Java classes where We need special purpose classes like StingBuilder and StringBuffer.
              > java.lang.StringBuilder#append() 
              > java.lang.StringBuffer#append() 
              > java.nio.ByteBuffer#put()


          Prototype:
          The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
          • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
          • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
          To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.
          The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.
          Example: Best example will be Java.lang.Object#clone() method. Class has be implement Cloneable interface to use this.  

          Structural Patterns

          Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities. These design patterns help us on similar programming structure in application and help us in application wide coding standard. 
          Adapter:
          the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer (i.e. flags) but the client requires individual boolean values, the adapter would be responsible for extracting the appropriate values from the integer value. Another example is transforming the format of dates (e.g. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).
          Example: Adapter Pattern is useful where we want to do integration from one format to another
            > java.util.Arrays#asList()
            > java.io.InputStreamReader(InputStream) (returns a Reader)
            > java.io.OutputStreamWriter(OutputStream) (returns a Writer)


          Facade:
          A facade Patern is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
          • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
          • make the library more readable, for the same reason;
          • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
          • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).
          Example: Facade pattern is used to make any library classes and It help us to build module as service. 
            > javax.servlet.http.HttpSession
           > javax.servlet.http.HttpServletRequest
           > javax.servlet.http.HttpServletResponse
           > javax.faces.context.ExternalContext

          Proxy:
          A proxy, in its most general form, is a class functioning as an interface to do something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
          A well-known example of the proxy pattern is a reference counting pointer object.
          In situations where multiple copies of a complex object must exist, the proxy pattern can be adapted to incorporate the flyweight pattern in order to reduce the application's memory footprint. Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.
          Example: This pattern is useful to create surrogate service, where client does not know about actual implementation.  java.rmi.* service uses Proxy pattern to communicate on network.

          Bridge:
          The bridge pattern is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulationaggregation, and can use inheritance to separate responsibilities into different classes.
          When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.
          The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class "adapter pattern", e.g. in the Java code below.
          Example: The Bridge pattern is an application of the old advice, "prefer composition over inheritance". It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape has a Color and to implement a hierarchy of colors, and that is the Bridge Pattern.

          Composite:
          Composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

          Component
          • is the abstraction for all components, including composite ones
          • declares the interface for objects in the composition
          • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
          Leaf
          • represents leaf objects in the composition .
          • implements all Component methods
          Composite
          • represents a composite Component (component having children)
          • implements methods to manipulate children
          • implements all Component methods, generally by delegating them to its children
          Example: This pattern is used in making Rule engine or validation pattern, where composite and single rule can be used in same way.

            Decorator:
            the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:
            1. Subclass the original "Decorator" class into a "Component" class (see UML diagram);
            2. In the Decorator class, add a Component pointer as a field;
            3. Pass a Component to the Decorator constructor to initialize the Component pointer;
            4. In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
            5. In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
            This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).
            The decorator pattern is an alternative to subclassing. Subclassing adds behavior atcompile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.
            This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.
            Example for this: Java collections object using Collections.synchronized() method to synchronize the collection at run time. All subclasses of java.io.InputStreamOutputStreamReader and Writer have a constructor taking an instance of same type. Another good example is javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper.

            Flyweight:
            A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.
            A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning.
            In other contexts the idea of sharing identical data structures is called hash consing.
            Sample Code for Fly weight pattern.
            Example :  This pattern is used with method overloading and  java.lang.Integer#valueOf(int) (also on BooleanByteCharacterShort and Long) is example of this.

            Part 2 Continues on Behavioural Patterns.


            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