Wednesday, June 3, 2015

Synchronization in Java

Each Java Virtual Machine executes many threads at once. All threads execute their internal code and operate their values in a shared memory space.
As we know, Synchronization is a process which executes only one thread at a time. To Synchronize, Java programming language uses monitors which is used to allow only one thread at a time to execute a region of code.
Monitors explained in terms of locks. The synchronized statement performs two special actions relevant only to multithreaded operation:
  1. after computing a reference to an object but before executing its body, it closes a lock associated with the object.
  2. after execution of the body has completed, either normally or abruptly, it unlocks that same lock
The methods wait, notify, and notifyAll of class Object support an efficient transfer of control from one thread to another.
Please see another article: Difference between JRE and JDK for further clarification of Java.

'is a' relationship and a 'has a' relationship in Java

 The is a relationship is expressed with inheritance and has a relationship is expressed with composition. 
Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.
e.g.,
is a --- House is a Building
class Building {
  .......
}
class House extends Building {
  .........
}
has a -- House has a bathroom
class House
{
  Bathroom room = new Bathroom() ;
  ....
  public void getTotMirrors()
  {
    room.getNoMirrors();
    ....
   }
 }
Inheritance Vs Composition
   
  Inheritance is uni-directional. 
 
   For example House is a Building. But Building is not a House. Inheritance uses
extends key word.

Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom.
 
Composition simply means using instance variables that refer to other objects. 
 
The class House will have an instance variable,which refers to a Bathroom object.

Immutable object in Java

Immutable objects whose state (i.e. the object’s data) does not change once it is instantiated (i.e. it becomes a read-only object after instantiation).
Immutable classes are ideal for representing numbers (e.g. java.lang.Integer, java.lang.Float, java.lang.BigDecimal etc are immutable objects), enumerated types, colors (e.g. java.awt.Color is an immutable object), short lived objects like events, messages etc.
The immutable class are written in following guidelines:
  1. A class is declared as final. (The final class cannot be extended)
  2. All its fields are final (final fields cannot be mutated once assigned).
  3. Do not provide any methods that can change the state of the immutable object in any way – not just setXXX methods, but any methods which can change the state.
  4. The “this” reference is not allowed to escape during construction from the immutable class and the immutable class should have exclusive access to fields that contain references to mutable objects like arrays, collections and mutable classes like Date etc by:
    • Declaring the mutable references as private.
    • Not returning or exposing the mutable references to the caller
Benefits:
  1. Immutable classes can greatly simplify programming by freely allowing you to cache and share the references to the immutable objects without having to
defensively copy them or without having to worry about their values becoming stale or corrupted.
  1. Immutable classes are inherently thread-safe and you do not have to
synchronize access to them to be used in a multi-threaded environment. So there is no chance of negative performance consequences.
  1. Eliminates the possibility of data becoming inaccessible when used as keys in HashMaps or as elements in Sets

Final variable

    A final variable behaves like a constant as its value never changes
    If a final variable is assigned, it always contains the same value.
    If final variable holds a reference to an object, then the state of the 
    object may be changed by the operations on object, but the variables will 
    refers to the same object. This applies also to arrays, because arrays are 
    objects; if a final variable holds a reference to an array, then the 
    components of the array may be changed by operations on the array, but the 
    variable will always refer to the same array.
 
    public class ExFinal
    {
      private final String name;
      private final String age;
      private final Object country ="India";  
      public ExFinal(String name, int age)
      {
          this.name = name;
          this.age = age;
      }
    public String toString()
    {
      return name + ", " + age + " " + " from " + " " +country;
    }
    }

Collections Framework in Java

Introduction to Collections framework in Java

The collections framework in Java refers to a commonality in implementation of the container classes (also referred to collection classes) such as Vector, Arrays, ArrayLists, LinkedList, Hashtable etc. which means that these can be manipulated independent of their representation using interoperability of unrelated APIs or use of common APIs.
The main advantage of this unified architecture is that by way of implementing one of the basic interfaces say Collection, Set, List or Map the user defined class conforms to a common API which can easily be reused and also understood properly.
The collections framework in Java is feasible because of design of the collection interfaces where the basic interface is collection itself. For instance, Set, List and SortedSets are extended interfaces of the collection interface. Other important container interfaces Map and SortedMap do not extend the collection interface but can be manipulated like collections.
The java classes that implement the collection interfaces have names in combination of type of implementation prefixed to the type of interface, for example,
  1. HashSet, TreeSet, LinkedHashset typical general purpose classes using Set interface.
  2. ArrayList and LinkedList classes using List interface.
  3. HashMap,TreeMap and LinkedHashMap using Map interface
The public interface Collection is the e root interface in the collection hierarchy and is part of java.util.Collection API.
All java developers know about the Collections Framework!
But, they are all know more and more things from Collection Frameworks.
Most of us know the concept of Collections like (What is Collection? and what is ArrayList?) but the implementations is very difficult when u are going to use in your applications.
Here I make few questions about this topic.
Before going to know about Collection Framework, we must know the What is Framework?
Framework make easier to work with complex technologies.
It is a architecture that manages the collection of Objects and implement the set of specific design elements.
I hope you are all understand about the Framework.
Now we can move to What is Collections Framework?
Collection Framework is a architecture that contains set of Classes and Interfaces for storing and manipulating the group of Objects.
Advantages of Collection Framework
  • Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself.
  • Increases performance by using data structures and algorithms.
  • Provides interoperability between unrelated APIs.
  • Reusability, standard interface for collections and algorithms to manipulate them.
Now we can see few things about Collection Framework,
Collections Framework for manipulating data collections.
When you are going to use the collections, you want to remember the following hierarchical relationship of the four basic interfaces of the framework,
  1. Collection ---> It is the root of the Collection hierarchy.
  2. Set ---> it is not allowed the duplicate elements.
  3. List ---> it is an Ordered Collection. It can contain duplicate elements.
  4. Map ---> It is store the Object as a Key, value pairs. It cannot contain duplicate keys; each key can map to at most one value.
  • Note-
Besides the Java Collections Framework, the other well known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy.
For reference:-
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html

ServletContext

Introduction

ServletContext Interface is used for sharing the information between all servlets in web application.
Through this interface, a Servlet can access raw input streams to Web Application resources, dispatch requests, a common mechanism for logging information, and an application scope for binding objects.

Description

A Servlet Context is used to maintain information for all instances of a Web application within any single JVM (that is, for all servlet and JSP page instances that are part of the Web application). There is one servlet context for each Web application running within a given JVM; this is always a one-to-one correspondence. You can think of a servlet context as a container for a specific application.
Servlet Context object provides information about the servlet environment such as name of the server) and allows sharing of resources between servlets in the group, within any single JVM. (For servlet containers supporting multiple simultaneous JVMs, implementation of resource-sharing varies.)

META-INF in Java

About JAR

JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one.
It is essentially a zip file that contains an optional META-INF directory.

About The META-INF Directory

META-INF directory is an optional directory structure contained in a JAR file, a file format containing java classes files and/or resources using the well-known ZIP file format.
A JAR file is normally created using a command-line jar tool or java.util.jar API in the Java package.
In META-INF directory, there is MANIFEST.MF file which is used to define extension and package related data and an INDEX.LIST file which contains location information for packages defined in an application or extension.
The INDEX.LIST file is normally generated using “–i” option of the jar command line tool. As a JarIndex implementation process it is used by class loaders to hasten the class loading process.
Other important files in META-INF Directory are x.SF and x.DSA where x stands for base file name. The x.SF is the signature file for the JAR file and the x.DSA is a signature block file related to the x.SF.
Also there exists a services sun directory in the META-INF Directory which stores all the service provider configuration files.

Summarized info. about META-INF

The META-INF Directory consists of the following files, which is used to configure the applications, extensions, class loaders and services:
  1. MANIFEST.MF ------> it is used to define extension and package related data.
  2. index.list ------> It contains the location information for packages defined in an application or extension.
    1. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.
  3. x.SF -------> The signature file for the JAR file. 'x' stands for the base file name.
  4. x.DSA --------> The signature block file associated with the signature file with the same base file name.
    1. This file stores the digital signature of the corresponding signature file.
  5. services/ -------> This directory stores all the service provider configuration files.
  • Note-
For further reference:-
http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html