Advertisements

Java Console Input Example


This is a simple example of taking console input and invoking a method based on the user inputs. There are many ways to do this and couple of them are listed below.

1) Using  simple    java.io.BufferedReader;
2) Using     java.io.Console;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
* Sample Console Input example
* @author manjul
*
*/
public class ConsoleInput {

public static void main(String[] args) throws IOException, InterruptedException {
  while(true){
  int in = takeInput();

  switch (in) {
   case 1:
   fun1();
   break;

   case 2:
   fun2();
   break;

   default:
   exit();
   break;
  }
}
}

private static int takeInput() throws IOException{
   StringBuilder sb = new StringBuilder();
   sb.append("Please Select an option: \n");
   sb.append("1: Show Songs\n");
   sb.append("2: Add Songs\n");
   sb.append("3: Exit \n");
   System.out.println(sb.toString());
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String input = br.readLine();
   System.out.println("You Selected: " + input);

   int in = -1;
   try{
    in = Integer.parseInt(input);
   }catch(Exception ex){
   System.out.println("Enter correct value [1,2,3]");
 }
   return in;
}

private static void fun1(){
   System.out.println("Heloo 1");
}

private static void fun2(){
   System.out.println("Hello 2");
}

private static void exit(){
   System.out.println("Thanks..");
   System.exit(1);
}

}

Advertisements

Hibernate Practicals

  1. Mapping One to Many
  2. Mapping Many to One
  3. Mapping Many to Many
  4. Cascade and Inverse = true

1: One to Many

One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. We already have seen how to map Set collection in hibernate, so if you already learned Set mapping then you are all set to go with one-to-many mapping.

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

create table CERTIFICATE (
   id INT NOT NULL auto_increment,
   certificate_name VARCHAR(30) default NULL,
   employee_id INT default NULL,
   PRIMARY KEY (id)
);

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <set name="certificates" cascade="all">
         <key column="employee_id"/>
         <one-to-many class="Certificate"/>
      </set>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>

   <class name="Certificate" table="CERTIFICATE">
      <meta attribute="class-description">
         This class contains the certificate records. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="name" column="certificate_name" type="string"/>
   </class>

</hibernate-mapping>
--------------------------------------------------------------------------------------

2: Many to One

many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example a same address object can be associated with multiple employee objects.

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   address    INT NOT NULL,
   PRIMARY KEY (id)
);

create table ADDRESS (
   id INT NOT NULL auto_increment,
   street_name VARCHAR(40) default NULL,
   city_name VARCHAR(40) default NULL,
   state_name VARCHAR(40) default NULL,
   zipcode VARCHAR(10) default NULL,
   PRIMARY KEY (id)
);

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
      <many-to-one name="address" column="address" 
       class="Address" not-null="true"/>
   </class>

   <class name="Address" table="ADDRESS">
      <meta attribute="class-description">
         This class contains the address detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="street" column="street_name" type="string"/>
      <property name="city" column="city_name" type="string"/>
      <property name="state" column="state_name" type="string"/>
      <property name="zipcode" column="zipcode" type="string"/>
   </class>

</hibernate-mapping>

--------------------------------------------------------------------------------------

3: Many to Many

Many-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. We already have seen how to map Set collection in hibernate, so if you already learned Set mapping then you are all set to go with many-to-many mapping.

Tables

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

create table CERTIFICATE (
   id INT NOT NULL auto_increment,
   certificate_name VARCHAR(30) default NULL,
   PRIMARY KEY (id)
);

create table EMP_CERT (
   employee_id INT NOT NULL,
   certificate_id INT NOT NULL,
   PRIMARY KEY (employee_id,certificate_id)
);

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <set name="certificates" cascade="save-update" table="EMP_CERT">
         <key column="employee_id"/>
         <many-to-many column="certificate_id" class="Certificate"/>
      </set>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>

   <class name="Certificate" table="CERTIFICATE">
      <meta attribute="class-description">
         This class contains the certificate records. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="name" column="certificate_name" type="string"/>
   </class>

</hibernate-mapping>

3: Casecade and Inverse=true

In case of many-to-many relation through intermediary table; “Cascade” says whether a record will be created/updated in the child table. Whereas “Inverse” says whether a record will be created/updated in the intermediary table

e.g. Assume below scenario 1 student can have multiple phones. So Student class has property for Set of phones. Also 1 Phone can be owned by multiple students. So Phone class has property for Set of Students. This mapping is mentioned in stud_phone table.

So there are three tables viz. Student, Phone and stud_phone (intermediary) table. Mapping might look like:

<set name="phoneset" table="stud_phone" cascade="save-update" inverse="true">
  <key column="mapping_stud_id">< /key>
  <many-to-many class="com.domain.Phone" column="mapping_phon_id"/>
</set> 

A new student object is created and 2 new phone objects are added to its set. Andsession.save(student_obj) is called. Depending upon “cascade” and “inverse” settings different queries will be fired.

Below are different combinations of cascade and inverse and their impact.

1) CASCADE IS NONE and INVERSE is false

Hibernate: insert into STUDENT (Name, stud_id) values (?, ?)
Hibernate: insert into stud_phone (mapping_stud_id, mapping_phon_id) values (?, ?)
Hibernate: insert into stud_phone (mapping_stud_id, mapping_phon_id) values (?, ?)

2) CASCADE is NONE and INVERSE is true

Hibernate: insert into STUDENT (Name, stud_id) values (?, ?)

3) CASCADE is save-update and INVERSE is false

Hibernate: insert into STUDENT (Name, stud_id) values (?, ?)
Hibernate: insert into phone (phone_num, phone_id) values (?, ?)
Hibernate: insert into phone (phone_num, phone_id) values (?, ?)
Hibernate: insert into stud_phone (mapping_stud_id, mapping_phon_id) values (?, ?)
Hibernate: insert into stud_phone (mapping_stud_id, mapping_phon_id) values (?, ?)

4) CASCADE is save-update and INVERSE true

Hibernate: insert into STUDENT (Name, stud_id) values (?, ?)
Hibernate: insert into phone (phone_num, phone_id) values (?, ?)
Hibernate: insert into phone (phone_num, phone_id) values (?, ?)

As it can be seen, only when CASCADE was save-update the records were created in PHONE table also. Otherwise not.

When INVERSE was false ( i.e. Student was the owner of relationship ) the intermediary table STUD_PHONE was updated. When inverse is true, Phone is owner of relationship, so even though a new student was created, the intermediary table was not updated.

So in case of relation of two entities, “cascade” affects other entity table and “inverse” affects intermediary table. So their effect is independent.

 

 

UML

UML concepts
  1. Dependency
  2. Aggregation
  3. Composition
Dependency is represented when a reference to one class is passed in as a method parameter to another class. For example, an instance of class B is passed in to a method of class A:
1
2
3
public class A {
    public void doSomething(B b) {

Now, if class A stored the reference to class B for later use we would have a different relationship calledAggregation. A more common and more obvious example of Aggregation would be via setter injection:

1
2
3
4
5
public class A {
    private B _b;
    public void setB(B b) { _b = b; }

Object which is being aggregated can also exist independently and its life cycle is not managed by parent object.

Aggregation is the weaker form of object containment (one object contains other objects). The stronger form is called Composition. In Composition the containing object is responsible for the creation and life cycle of the contained object. Following are a few examples of Composition. First, via member initialization:

1
2
3
public class A {
    private B _b = new B();

Second, via constructor initialization:

Spring MVC quick overview

Spring provided MVC based architecture for Web applications:

1. The Model encapsulates the application data and in general they will consist of POJO.
2. The View is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.
3. The Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.

When application receives a request it goes through below flow:
1. Dispatcher servlet passes request to specific controller after checking with HandlerMappings
2. Controller takes the request and calls the appropriate service method for GET or POST request
3. Service methods sets the data model based on the business logic provided and returns the View name to dispatcher servlet.
Note : Here Model Object is an input parameter and it is updated are required. ONLY view is returned

4. Dispatcher servlet consult viewresolver to find the specific view.
5. Once view is specific then Dispatcher servlet passes the Model object to the view object which finally renders the data.

NOTE:

A )Spring allows you to bring multilevel context hierarchy where a bean is fetched from parent context if it is not available in current context
B) It is good to create two context one for WEB components and another for Core Components live services and DAOs

1: Dispatcher Servlet Configuration in web.xml
Screen Shot 2014-01-06 at 12.11.14 AM
ROOT CONTEXT : This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml

 
FOR ROOT APPLICATION CONTEXT configuration
Screen Shot 2014-01-06 at 12.13.49 AM

2: Hander mappings and controller
We can specify handler mapping in servlet-config or we can also specify Annotation based mapping.
a) XML based mapping
Screen Shot 2014-01-06 at 12.18.47 AM
b) Annotation based mapping

@Controller
@RequestMapping("/login.htm")
public class LoginController {

@RequestMapping(value="/loginController.htm", method = RequestMethod.GET)
	public String loginCheck(Model map,HttpServletRequest request){

	//your business logic
}

handler methods are annotated with @RequestMapping and they are flexible to accept any arguments. Example:
• HttpServletRequest
• HttpSession
• java.io.InputStream / java.io.Reader for access to the request’s content.
• java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap
Handler methods can return followings types
• A ModelAndView object
• A Model object, with the view name implicitly determined through a RequestToViewNameTranslator
• A View object, with the model implicitly determined through command objects and @ModelAttribute
• A String value which is interpreted as view name, …
• void if the method handles the response itself

3: View Resolver: Viewresolver technology helps to resolve the view page to be rendered by the

@Controller

4: Spring MVC Interceptors
Spring mvc allows you to intercept web request through handler interceptors. This interface has three methods.
1. preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.
2. postHandle() – Called after the handler execution, allow manipulate the ModelAndView object before render it to view page.
3. afterCompletion() – Called after the complete request has finished.

Example : In this example HandlerInterceptor is intercepting preHandleRequest to check its method type and fetch CSRF token from request and passing if available.

public class CSRFHandlerInterceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!request.getMethod().equalsIgnoreCase("POST") ) {
    // Not a POST - allow the request
    return true;
} else {
   // This is a POST request - need to check the CSRF token
    String sessionToken = CSRFTokenManager.getTokenForSession(request.getSession());
    String requestToken = CSRFTokenManager.getTokenFromRequest(request);
    if (sessionToken.equals(requestToken)) {
      return true;
    } else {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
    return false;
 }
}
}
}

Define Servlet Config ; Servlet Context; Servlet Listener ; Servlet Filters

1: Servlet Config is the object is used by servlet container to pass information to servlet object when it is initialised. There is single servlet config object for each servlet.
Web.xml:

Screen Shot 2013-12-25 at 11.02.20 PM

Accessing its value in servlet:

public class MyServlet extends HttpServlet  
{  
    public void init(ServletConfig config) throws ServletException {  
        String initParam  = config.getInitParameter("InitParamA");  
    }  
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        String initParam = getServletConfig().getInitParameter("InitParamA");  
        ...  
    }  
    ...  
}

2: ServletContext : Defines set of methods used to communicates with the servlet containe. There is ONE ServletContext per web application.
In the case of a web application marked “distributed” in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won’t be truly global). Use an external resource like a database instead. Note: ServletContext==ApplicationContext

Web.xml

Screen Shot 2013-12-25 at 11.02.38 PM

Accessing it from Servlet
public void init(ServletConfig config) throws ServletException {  
        String contextParam = config.getServletContext().getInitParameter("ContextParamA");  
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        String contextParam = this.getServletContext().getInitParameter("ContextParamA");  
        ...  
    }

3: Servlet Listener: Servlet API provides various listener interface to handle different types of events like servlet initialisation/destroy etc and do certain operations on these events. Some of the listeners interfaces are
javax.servlet.AsyncListener
javax.servlet.ServletContextListener
javax.servlet.ServletRequestListener
javax.servlet.http.HttpSessionListener
etc

Implementing Listener class has to be configured in web.xml
Web.xml

Screen Shot 2013-12-25 at 11.03.05 PM

Example of ServletContextListener

public class AppContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();

        String url = ctx.getInitParameter("url");
        String uname = ctx.getInitParameter("uname");
        String pwd = ctx.getInitParameter("pwd");

        DBConnectionManager dbManager = new DBConnectionManager(url, uname, pwd);
        ctx.setAttribute("DBManager", dbManager);
       //"Database connection initialized for Application.
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        DBConnectionManager dbManager = (DBConnectionManager) ctx.getAttribute("DBManager");
        dbManager.closeConnection();
        //Database connection closed for Application.

    }    
}

4 Servlet Filters: Servlet filter is an object which performs filtering task on request or response or both. Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.

Filters are configured in the deployment descriptor of a web application

Some of the common places where filters can be used:
1) Authentication Filters
2) Logging and Auditing Filters
3) Image conversion Filters
4) Data compression Filters
5) Encryption Filters
6) Mime-type chain Filter
etc

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class
public class MyFilter implements Filter  {
   public void  init(FilterConfig config)
                         throws ServletException{
      // Get init parameter
      String testParam = config.getInitParameter("test-param");

      //Print the init parameter
      System.out.println("Test Param: " + testParam);
   }
   public void  doFilter(ServletRequest request,
                 ServletResponse response,
                 FilterChain chain)
                 throws java.io.IOException, ServletException {

      // Get the IP address of client machine.   
      String ipAddress = request.getRemoteAddr();

      // Log the IP address and current timestamp.
      System.out.println("IP "+ ipAddress + ", Time "
                                       + new Date().toString());

      // Pass request back down the filter chain
      chain.doFilter(request,response);
   }
   public void destroy( ){
      /* Called before the Filter instance is removed
      from service by the web container*/
   }
}

Filter configuration in web.xml is very similar as servlet configuration.

Web.xml

Screen Shot 2013-12-26 at 11.54.21 PM

readObject() and writeObject() &nd; readResolve()

There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

  • private void writeObject(ObjectOutputStream out) throws IOException;
  • private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal. The serialization protocol is always used the same way, by calling either ObjectOutputStream.writeObject() or ObjectInputStream.readObject(). So, even though those specialized private methods are provided, the object serialization works the same way as far as any calling object is concerned.

ref:http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html

readResolve is called after readObject has returned (conversely writeReplace is called before writeObject and probably on a different object). The object the method returns replaces this object returned to the user of ObjectInputStream.readObject and any further back references to the object in the stream. It is mostly used for serial proxies for example in case is Singleton class if it is serializable then we need to specify in readResolve that it returns singleton object and not the one which is read from persisted location.

Producer Consumer Problem Solution Example in Java

This is a simple example of Producer and Consumer problem, where Producer created and puts data in a shared list but waits if the list is full. Similarly Consumer consumes data from the list but waits if the list is empty


import java.util.ArrayList;
import java.util.List;

class Pool{
	List list = new ArrayList();
	int MaxSize= 5;

	synchronized String getData() throws InterruptedException{
		if(list.isEmpty()){
			System.out.println("Get Data List is empty, wait please");
			wait();
			return null;
		}
		System.out.println("Get Data done: " + list.get(0));
		notifyAll();
		return list.remove(0); 
	}

	synchronized boolean setData(String str) throws InterruptedException{
		if(list.size()>=MaxSize){
			this.wait();
			System.out.println("Set Data , List is full please wait");
			return false;
		}else{
			System.out.println("Set Data , Data added > " + str);
		}
		list.add(str);
		notifyAll();
		return true;
	}

}
class Producer extends Thread{
	Pool pool;
	Producer(Pool pool){
		this.pool = pool;
	}

	@Override
	public void run() {
		for(int i=1; i<=70; i++){
			try {
				if(!this.pool.setData(i+"")){
					i--;
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

}

class Consumer extends Thread{
	Pool pool;
	Consumer(Pool pool){
		this.pool = pool;
	}
	@Override
	public void run() {
		while(true){
			String i;
			try {
				i = this.pool.getData();
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
}

public class ProducerConsumerTest {
	public static void main(String[] args){
			Pool pool = new Pool();
			Producer pro = new Producer(pool);
			Consumer con = new Consumer(pool);
			pro.start();
			con.start();
	}
}

Java Concurrency in Practice

Concurrent programming covers concept of parallel program execution, inter process or thread communication, shared object , thread executor frame work, future and callable objects etc.

In this article we would cover following concepts :

  1. What is concurrency
  2. Process and Threads
  3. Thread communication
  4. Synchronization and Locking
  5. Atomic variable, Volatile variable and Semaphores
  6. Immutable objects
  7. High level of concurrency
  8. Executor framework
  9. Future and Callable objects
  10. Concurrent Collection

1: What is Concurrency: Concurrency means ability to run various part of a program parallely. Classic example is your mobile phone where you can talk while while accessing net and your phone pops out any live notifications without waiting any process to complete. So in other words these set of process are running parallel and this is called concurrency.

Java Provides set of APIs to write concurrent programming application that we would cover in this article.

2: Process and Threads: Java Process are same as any other operating system process, they have their own memory allocation and own set of resources. This is a simple example to show how can you create a process using Java API to invoke any OS level command.


public static void main(String[] args){
		try {
			Process p = new ProcessBuilder("ls", "-l").start();
			BufferedInputStream bin = new BufferedInputStream(p.getInputStream());
			InputStreamReader inReader = new InputStreamReader(bin);
			BufferedReader reader = new BufferedReader(inReader);
			String line;
			while((line = reader.readLine())!=null){
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Threads on the other hand are light weight processes which are created from a single parent process. Threads can share all resources belong to its parent thread or process and they occupy less memory with respect to the process.

Java API provides two ways to create threads

  • Implementing Runnable Interface
  • Extending Thread Class

We all know about them so I am not going in deep of them.

3: Thread Communication: Thread communication means all possible ways by which threads can send signals to each other and do some work in specified or synchronized manner. For example suppose there are some Producers and Consumers for some goods for a particular Store. So here Producer can produce so item only if store is not FULL otherwise Producer would wait till Consumer consumes some of the products . Same way for Consumer they can consume only if  that Store is not empty or else they would have to wait till a Producer produces some products.

Some common ways of thread communications are described here:

-Thread.sleep(milliseconds) This way is not very efficient but still a possible way where you put a Thread in sleep based on some condition. This would invoke the thread after specified time and check again if the condition is satisfied or not.    ex:   if(condition) then Thread.sleep(millisecond);

-Wait/Notify/Notify All: A Thread  can invoke Object.wait() method if any condition is not satisfied and this would put that thread in wait condition. When some other Second thread invokes Notify or Notify All then previous thread/s would be notified, here this second thread might change the conditional state which would enable previous thread to resume their execution once they are notified.

-CountDownLatch/CyclicBarrier: A Synchronization technique which allows one or more thread to wait until some specified no of tasks are performed by another thread.

CountDownLatch signal = new CountDownLatch(N);

CountDownLatch is initialized with some counter value. A thread which invokes signal.await(); get blocks until current count reaches zero by some other thread by calling signal.countDown()

-Semaphore: It also little bit similar concept as CountDownLatch but rather storing any counter value a semaphore maintain set of permits (like tokens). A thread has to acquire a permit before executing some exclusive section and after its execution is complete it has to release the permit. This approach is useful in cases where there are fixed no of worker threads has to work on a task.

Semaphore available = new Semaphore(MAX_AVAILABLE, true);

A semaphore which is initialized with value one can serve for mutual exclusion execution where at a time only one thread can enter the execution after accruing the required permit from semaphore.

4: Synchronization and Locking : When multiple thread are accessing a shared resource then in order to maintain its data integrity it is necessary that at a time only one thread is accessing or updating the resource. There are two ways of basic synchronization which are  achieved with the help of intrinsic Lock associated an Object.

Method Synchronization: We can make whole method synchronized and the running thread would take lock on the object which owns that method.

public synchronized int getCounter (int value) {
//method code
}

Synchronized Block : If we don’t want to make whole method as synchronized then we can put the set of statements in synchronized block which we want to be executed by single thread a time. Not to mention that we should prefer synchronized block over method as they reduces size of synchronized code. Unnecessary synchronized code is always a processing overhead so keep it minimal.

synchronized(Object) {
// statements to be synchronized
}

5: Atomic variable, Volatile variable and Semaphores: 

Atomic variables:  Java has provided set of classes in java.util.concurrent.atomic package, these classes have get and set methods which works like reading and writing on Volatile variables. Basically they ensure that all update operations should work in atomic manner even if they are not put in manual synchronized.

Volatile variable: If a thread access some variable usually they keep them in their local cache. But if want to enforce that thread should always read that variable from main memory whenever they access then we can mark it as volatile.

private volatile int counter;

Java 5 guarantees that write(update) to any volatile variable happens before any concurrent read. This becomes very important where all reader threads do not acquire any locking and until writer thread comes out of the synchronization block they can still use old value.  Note: Volatile can not be used with classes or methods so they are not the replacement of synchronized section.

Semaphore: It also little bit similar concept as CountDownLatch but rather storing any counter value a semaphore maintain set of permits (like tokens). A thread has to acquire a permit before executing some exclusive section and after that it has to release the permit. We have explained in detail in Inter Thread Communication Section.

6: Immutable objects: In some cases we my not want to allow to change the state of the object once it created example String class is immutable class. Immutable objects can not be modified so they are automatically thread safe in con current execution.

Read more about immutable class in my another section :Guidelines to write immutable classes.

=====================================================================================

7: High level of concurrency: Java 5 onward version has very good built in APIs to support advance level of concurrency. High level concurrency provides following components :

-Locks: java.util.concurrent.locks.*  package. So far we have used Java implicit lock which is simple to use but has some limitations. Java concurrent Locking API provides more versatile Lock interface and its implementations ReadWriteLock , RenterantLock which also works like implicit Object Lock. We would cover it in detail in my another article. Here is small code to using Lock Api.


       //Creating Lock object 
       private final Lock lock = new ReentrantLock();
       Boolean myLock = false;
       //accruing the lock
       myLock = lock.tryLock();
       //releasing the lock
       lock.unlock();

-Executors:  So far Threads were sufficient for simple applications for concurrent programming. In highly complex and lag application it is difficult and complex to do thread management by ourselves. Java API 5 onward has built in framework  to create , maintain the set of threads and their life cycle. Our job is to provide them a Runnable worker Object for business processing.

Executor Interface: java.util.concurrent package has defined three executor interfaces. Executor provides simple method e.execute() which is equivalent to new Thread(runnable).start() call.

1:Executor interface support launching of new tasks by its execute method.

2:ExeutorService, sub interface of executor which can manage life cycle of both task and executor. It supplements execute method with similar submit method: <T> Future submit(Runnable task, T result). Here return types Futures object’t get method would return the result on successful execution.

3:ScheduledExecutor is sub interface of ExecutorService which additionally allows to run a callable or runnable object after specified delay or periodically.

ThreadPool: Most of the executor implementation use ThreadPool which consist of number of worker thread which can execute a runnable task. This reduces the overhead of thread creation and thread life cycle management in large application.

Example:

 
         public static void main(String[] args) {
          //Specify a RejectedExecutionHandler to handle the task in case they are rejected by thread pool when Queue is also fulled.
          RejectedExecutionHandler rejHandler = new PoolRejectHandler();
          // specify default size of ThreadPool
          int coreSize=10;
          // specify maximum size of Thread Pool
          int maxSize = 50;
          int keepAliveTime = 900;
          // specify the Queue to hold runnable objects while no of threads exceeds to Default Pool Size
          BlockingQueue queue = new LinkedBlockingDeque(200);
          ThreadPoolExecutor pool = new ThreadPoolExecutor(coreSize, maxSize, keepAliveTime, TimeUnit.MILLISECONDS,
 queue, rejHandler);
          Runnable worker = new Worker();
          //execute the runnable task
          pool.execute(worker);
          }

-Future and Callable Objects: Future Interface represents the result of an asynchronous call. It provides methods to check if the computation is complete, to wait for its completion or to retrieve the result of the computation. This is the object which is return by the ExecutorService submit method, it can be used for doing post processing once thread’s execution is over.

Callable:A task that returns a result and may throw an exception. Implements define a single method with no arguments called call. This is a supplement to Runnable and can be passed in Executor.submit() method.

10: Concurrent Collections: JAVA API has given several ready to use concurrent collection in java.util.concuttent package. These collections can be categorized by thee main interface they implement .

BlockingQueue: It is sub interface of Queue and in addition it provides get() and put() . get() method would wait of the queue is empty and put method would wait if the queue is full. Hence no need to put additional monitors wile working with multiple threads. LinkedBloackingQueue and ArrayBlocking Queue are popular implementation of this.

ConcurrentMAP: This is sub interface of java.util.Map, that defines useful Atomic operation. That means remove or replace key value only if key-value is present or add key-value only if key is absent. Making these operations atomic in nature helps to avoid need of synchronization.   Popular implementation of ConcurrentMap is Concurrent HashMap.

-ConcurrentNavigableMap: This is third interface provided in Concurrent package how ever this is not very much popular as above two interfaces. This supports approximate match and its popular implementation is ConcurrentSkipListMap

 

Why Object class clone method is protected.

This is one of the tricky but frequently asked question.

Objects class’s clone method is protected and by default clone method is not visible and not available outside the class, there must be some reason behind this design. The reason is before making clone method available to use; a class has to implement  Cloneable interface first and override its clone method and then it is the responsibility of the class to expose this method through any other public method or by making the @Overriden clone method itself public.

SALLOW or DEEP Cloning?

Object class provide implementation of clone method and by default it provides SHALLOW  cloning , it simply creates a new instance and simply copies all the fields into new instance.  Standard way of providing Shallow cloning is to call super.clone() from the overridden clone method, that’s all it will do the job for you. Note all primitive data would get copy but  if there are any object   fields in your class then only their reference would be copied to the cloned object .


@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}

If you want to deep cloning in that case you need to override  the clone  method  and need to  give your own implementation of clone. Rather calling super.clone you  have to copy all NON MUTABLE  fields explicitly.

Typical example here you can see class Person contains object of class Mobile which further hold a Map collection. While doing Deep cloning of Person class we need to explicitly tell clone method to create new objects for its MUATBLE fields: Student and phonebook MAP. So we can not pass their reference during DEEP cloning.

//Deep Cloning Example
class Mobile{
	int mobileNo;
	Map<String, Integer> phoneBook;
	Mobile(int mobileNo,Map<String, Integer> phoneBook ){
		this.mobileNo=mobileNo;
		this.phoneBook=phoneBook;
	}

}
class Person{
	int age;
	String name;
	Mobile mobile;
	public Person(int age, String name, Mobile mobile) {
		super();
		this.age = age;
		this.name = name;
		this.mobile = mobile;
		System.out.println("Constrct call P1");
	}

//	@Override
//	public Object clone() throws CloneNotSupportedException {
//		return super.clone();
//	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		Map<String, Integer> newphoneBook = new HashMap<String, Integer>();
		//copy content of phoneBook
		for(String key : this.mobile.phoneBook.keySet() ){
			newphoneBook.put(key, this.mobile.phoneBook.get(key).intValue());
		}
		//create new mobile object with copied value of phone book
		Mobile mobile = new Mobile(this.mobile.mobileNo, this.mobile.phoneBook);
		//create new instance of person and copy these new field values
		return new Person(this.age, this.name, this.mobile);
	}

}

What is the purpose of calling Super.clone() from clone method?

By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case thatx.clone().getClass() == x.getClass(). This way you do not need to implement clone method for shallow cloning.

By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal “deep structure” of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.cloneneed to be modified.

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a “shallow copy” of this object, not a “deep copy” operation.

Ref:http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone()

Simple Combination Generation Algorithm.

Some times we come across situation of generating all possible combinations of given set of values or objects. One classical example of combination without repetition is Lottery System where lotteries are listed for all possible number combination but the one lucky combination wins that.

Another example of combination is number lock where we set a number combination as a key.Whichever be the need below is a simple algorithm of creating combination.

Combination means all possible arrangements of given set of values or objects.

Combinations2

Suppose we have been given set of some words or numbers or say letters like {a,b,c,d}. Then think how do we practically crate a combination.. Answere is you would probably pick an item say a

a,,,,

then you may place another item in the available space ex:

a,,b,

then you would put c and d.

a,c,b,

and then

a,c,b,d

This is how you have achieved one combination where we put first element ‘a’ at first position and arranged other three elements at vacant positions one by one. Like wise in next iteration we can place a at second positions and again place all element one by one in vacant positions.

We have mode this practical approach in algorithm where we pick first item and put in all possible positions and then pick second element and put in all possible positions.

We are using approach or recursion where we first position first element ‘a’ in all available possible position one by one in a loop and then we call subsequently same approach for other elements one by one. Simple here you go !

Here is a simple code written for this algorithm.



import java.util.Arrays;
public class PasswordGen {
static String[] options = {"a","b","c","d"};
static String[] places = new String[options.length];
static int count;

public static void main(String [] args){
  //Starting with initial position of a i.e. 0
  sequence(0,places.clone());
}

private static void sequence(int level, String[] holder){
  if(level>=options.length){
    //combination complete
    System.out.println(""+(++count) + " Combination " + Arrays.toString(holder));
    return ;
  }

  String val = options[level];
  String[] inrHolder = null;
  for(int c=0; c<holder.length; c++){
    inrHolder = holder.clone();
    if(inrHolder[c]==null){
      inrHolder[c]=val;
      sequence(level+1, inrHolder.clone());
    }
  }
  return ;
}
}



Output of the above program tested for sample a,b,c,d :

1 Combination [a, b, c, d]
2 Combination [a, b, d, c]
3 Combination [a, c, b, d]
4 Combination [a, d, b, c]
5 Combination [a, c, d, b]
6 Combination [a, d, c, b]
7 Combination [b, a, c, d]
8 Combination [b, a, d, c]
9 Combination [c, a, b, d]
10 Combination [d, a, b, c]
11 Combination [c, a, d, b]
12 Combination [d, a, c, b]
13 Combination [b, c, a, d]
14 Combination [b, d, a, c]
15 Combination [c, b, a, d]
16 Combination [d, b, a, c]
17 Combination [c, d, a, b]
18 Combination [d, c, a, b]
19 Combination [b, c, d, a]
20 Combination [b, d, c, a]
21 Combination [c, b, d, a]
22 Combination [d, b, c, a]
23 Combination [c, d, b, a]
24 Combination [d, c, b, a]

Blog Likes

  • 23,407 Likes