Sunday, April 19, 2015

Classification of Design Pattern in Software Development

Classification of  Software Design Pattern
Purpose
[reflects what a pattern does]
Creational
[concern the process of object creation]
Structural
[deal with the composition of classes or objects]
Behavioral
[characterize the ways in which classes or objects interact and distribute responsibility]
Scope
[specifies whether the pattern applies
primarily to classes or to objects]
Class
[deal with relationships between classes and their subclasses. These relationships are established through inheritance, so they are static—fixed at compile-time
]
Factory Method

[Class-creational patterns deal with Class-instantiation. They defer their object creation to subclasses.]
Adapter

[The Structural class
patterns use inheritance to compose classes]
Interpreter
Template Method

[Behavioral class patterns use inheritance to describe algorithms and flow of control]
Object
[Object patterns deal with object relationships, which can be changed at run-time and are more dynamic]
Abstract Factory
Builder
Prototype
Singleton

[Object-creational patterns deal with Object creation. They defer the part of their object creation to another object]
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy

[the Structural object patterns describe ways to assemble objects]
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
[the Behavioral object patterns describe how a group of objects cooperate to perform a task that no single object can carry out alone]

Thursday, April 16, 2015

Design Patterns

Design patterns are useful because they provide a pre-formulated solution to problems based on the experience of other programmers. This can save you a lot of time.
Design patterns also help in communication of a programming solution, and provide a common technical vocabulary between programmers.
Design pattern and Framework are not same thing. Design patterns are more like general guidelines on how to solve specific programming problems, but they do not specify the detailed code that’s necessary to solve those problems.
 Of course, using the wrong design pattern can have a very negative effect on your code. So, it takes good judgement to use the correct design pattern. The term “anti-pattern” is used to describe a poor programming practice that leads to ineffective code.

In general, a pattern has four essential elements:
1.The pattern name is a handle we can use to describe a design problem
2.The problem describes when to apply the pattern. It explains the problem and its context.
3.The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations.
4.The consequences are the results and trade-offs of applying the pattern.


We classify design patterns by two criteria (Table 1.1). The first criterion,  called purpose, reflects what a pattern does. Patterns can have either creational,  structural, or behavioral purpose. Creational patterns concern the process of  object creation. Structural patterns deal with the composition of classes or  objects. Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility.

The second criterion, called scope, specifies whether the pattern applies primarily to classes or to objects. Class patterns deal with relationships between classes and their subclasses. These relationships are established through inheritance, so they are static—fixed at compile-time. Object patterns deal with object relationships, which can be changed at run-time and are more dynamic. Almost all patterns use inheritance to some extent. So the only patterns labeled "class patterns" are those that focus on class relationships. Note that most patterns are in the Object scope.

Creational class patterns defer some part of object creation to subclasses, while Creational object patterns defer it to another object. The Structural class patterns use inheritance to compose classes, while the Structural object patterns describe ways to assemble objects. The Behavioral class patterns use inheritance to describe algorithms and flow of control, whereas the Behavioral object patterns describe how a group of objects cooperate to perform a task that no single object can carry out alone.

Sunday, April 12, 2015

Perm Space in Java

It stands for permanent generation.

The permanent generation is special because it holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause java.lang.OutOfMemoryError: PermGen no matter how high your -Xmx and how much memory you have on the machine.

The permanent Generation contains the following class information:
  • Methods of a class.
  • Names of the classes.
  • Constants pool information.
  • Object arrays and type arrays associated with a class.
  • Internal objects used by JVM.
  • Information used for optimization by the compilers.
‘Java.Lang.OutOfMemoryError: PermGen Space’ occurs when JVM needs to load the definition of a new class and there is no enough space in PermGen. The default PermGen Space allocated is 64 MB for server mode and 32 MB for client mode. There could be 2 reasons why PermGen Space issue occurs.
The 1st reason could be your application or your server has too many classes and the existing PermGen Space is not able to accommodate all the classes. And the 2nd reason could be memory leak. How the class definitions that are loaded could can become unused.

Friday, April 10, 2015

Heap Space in Java

When a Java program started Java Virtual Machine gets some memory from Operating System. Java Virtual Machine or JVM uses this memory for all its need and part of this memory is call java heap memory. Heap in Java generally located at bottom of address space and move upwards. whenever we create object using new operator or by any another means object is allocated memory from Heap and When object dies or garbage collected ,memory goes back to Heap space in Java.

1. Java Heap Memory is part of memory allocated to JVM by Operating System.


2. Whenever we create objects they are created inside Heap in Java.

3. Java Heap space is divided into three regions or generation for sake of garbage collection,called New Generation, Old or tenured Generation or Perm Space. Permanent generation is garbage collected during full gc in hotspot JVM.

4. You can increase or change size of Java Heap space by using JVM command line option -Xms, -Xmx and -Xmn. don't forget to add word "M" or "G" after specifying size to indicate Mega or Gig. for example you can set java heap size to 258MB by executing following command java -Xmx256m HelloWord.

5. You can use command "jmap" to take Heap dump in Java and "jhat" to analyze that heap dump.

6. Java Heap space is different than Stack which is used to store call hierarchy and local variables.

7. Java Garbage collector is responsible for reclaiming memory from dead object and returning to Java Heap space.

8. Don’t panic when you get java.lang.OutOfMemoryError, sometimes its just matter of increasing heap size but if it’s recurrent then look for memory leak in Java.

9. Use Profiler and Heap dump Analyzer tool to understand Java Heap space and how much memory is allocated to each object.



ArrayList, LinkedList, and Vector

ArrayList, LinkedList, and Vector are all implementations of the List interface.

ArrayList and Vector each use an dynamic array to store the elements of the list. Bother Vector and ArrayList are derived from AbstractList and implements List interface, which means both of them are ordered collection and allows duplicates. Another similarity between Vector vs ArrayList is that both are index based Collection and you can use get(index) method to retrieve objects from Vector and ArrayList. When an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.There is a different in Data Growth method for ArrayList and Vector also. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.


LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.


Among them, LinkedList is generally going to give you the best performance.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

Thursday, April 9, 2015

Java Collection


Some key information on Collection:

  • List can contain duplicate elements whereas Set contains only unique elements.
  • Set contains values only whereas Map contains key and values both.
  • HashSet maintains no order whereas TreeSet maintains ascending order.
  • HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.
  • HashMap maintains no order but TreeMap maintains ascending order.
  • Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

Thread Safety in Java

Thread safety is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe. Concurrent programming is bounded by the norms of thread safety.

Code that is safe to call by multiple threads simultanously is called thread safe. If a piece of code is thread safe, then it contains no race conditions. Race condition only occur when multiple threads update shared resources. Therefore it is important to know what resources Java threads share when executing.

Each thread has its own stack. Two different threads never shares the same stack. All local variables defined in a method will be allocated memory in stack. As soon as method execution is completed by the current thread, stack frame will be removed. So, local variables are thread safe in Java. If an object created locally never escapes the method it was created in, it is thread safe.Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack.


  • Synchronization is the easiest and most widely used tool for thread safety in java.
  • Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
  • Use of locks from java.util.concurrent.locks package.
  • Using thread safe collection classes, i.e ConcurrentHashMap for thread safety.
  • Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.

Tuesday, April 7, 2015

Life Cycle of Servlet

The following figure depicts a typical servlet life-cycle scenario.
  • First the HTTP requests coming to the server are delegated to the servlet container.
  • The servlet container loads the servlet before invoking the service() method.
  • Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.

  • The servlet is initialized by calling the init () method.
  • The servlet calls service() method to process a client's request.
  • The servlet is terminated by calling the destroy() method.
  • Finally, servlet is garbage collected by the garbage collector of the JVM

Monday, April 6, 2015

JVM, Java Processor

Every Java program is first compiled into an intermediate language called Java bytecode. 
The JVM is used primarily for 2 things:

1. The first is to translate the bytecode into the machine language for a particular computer,
2.The second thing is to actually execute the corresponding machine-language instructions as well. 

The JVM and bytecode combined give Java its status as a "portable" language – this is because Java bytecode can be transferred from one machine to another.

Machine language is OS dependent

Given the previous information, it should be easier to figure out an answer to the original question. Since the JVM must translate the bytecode into machine language, and since the machine language depends on the operating system being used, it is clear that the JVM is platform (operating system) dependent – in other words, the JVM is not platform independent.

Almost all JVMs are implemented in software. However, a JVM is anything that interprets Java bytecode in a manner that complies with the JVM specification, and there are some hardware-based JVMs as well.
Java processor is the implementation of the Java Virtual Machine (JVM) in hardware. In other words the bytecodes that make up the instruction set of the abstract machine become the instruction set of a concrete machine. These are today the most popular form of a high-level language computer architecture.

Creating a thread in Java; Two ways; Why

To define a class that is a derived from the Thread class which is built into Java. An object of this derived class will be a thread. Thread class has a method called run, which you must override in order to have your thread do whatever you want it to do.

Java does not support multiple inheritance, which means that we can not derive from multiple classes at once. So, there may be a situation in which we want to create a thread, but we also want to derive from a class that is not the Thread class. For this reason, Java provides an alternative way of creating a thread – so that you don’t have to create a class that derives from the Thread class. Java provides an interface called Runnable that our class can implement in order to become a thread. The Runnable interface has only one method heading that we must implement .

Sunday, April 5, 2015

Difference between equals() and == in Java

Before discussing the difference between “==” and the equals() method, it’s important to understand that an object has both a location in memory and a specific state depending on the values that are inside the object.

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory.

The equals method is defined in the Object class, from which every class is either a direct or indirect descendant.By default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal.
For example:
String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!
Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

What’s the point of having a private constructor in Java?

There are two possible reasons why one would want to use a private constructor – the first is that you don’t want any objects of a class to be created at all, and the second is that we want objects to be created internally – as in only created in our class.

Defining a constructor with the private modifier says that only the native class (as in the class in which the private constructor is defined) is allowed to create an instance of the class, and no other caller is permitted to do so.

To implement a singleton design pattern that allows only one instance of a class to be created, and this can be accomplished by using a private constructor.

Java always provides a default, no-argument, public constructor if no programmer-defined constructor exists. Creating a private no-argument constructor essentially prevents the usage of that default constructor, thereby preventing a caller from creating an instance of the class. Note that the private constructor may even be empty.