Monday, December 26, 2016

Java Interview Latest Questions

      1) How hash map works internally.
Refer homeshop 18 post

2) Hbm cache – difference
First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.


First-level cache - First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

3) What is Connection pooling?
Ans:
import java.sql.*;
import javax.sql.*;

public class JDBCServlet extends HttpServlet {

  private DataSource datasource;

  public void init(ServletConfig config) throws ServletException {
    try {
      // Look up the JNDI data source only once at init time
      Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
      datasource = (DataSource) envCtx.lookup("jdbc/MyDataSource");
    }
    catch (NamingException e) {
      e.printStackTrace();
    }
  }

  private Connection getConnection() throws SQLException {
    return datasource.getConnection();
  }

  public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
    Connection connection=null;
    try {
      connection = getConnection();
      ..<do JDBC work>..
    } 
    catch (SQLException sqlException) {
      sqlException.printStackTrace();
    }
    finally {
      if (connection != null) 
        try {connection.close();} catch (SQLException e) {}
      }
    }
  }
}

4) Explain Spring bean life cycle.

Here is the content of HelloWorld.java file:
package com.dev21century;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}
Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.
package com.dev21century;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {

      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}
Following is the configuration file Beans.xml required for init and destroy methods:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld"
       class="com.dev21century.HelloWorld"
       init-method="init" destroy-method="destroy">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:
Bean is going through init.
Your Message : Hello World!
Bean will destroy now.
Default initialization and destroy methods:
If you have too many beans having initialization and or destroy methods with the same name, you don't need to declare init-method and destroy-methodon each individual bean. Instead framework provides the flexibility to configure such situation using default-init-method and default-destroy-methodattributes on the <beans> element as follows:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    default-init-method="init"
    default-destroy-method="destroy">

   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

</beans>

5) XmlBeanFactory uses
Ans: ApplicationContext is a sub-interface of BeanFactory.You can use this way
public class SpringHelloWorldTest {
    public static void main(String[] args) {
        ApplicationContext context= new ClassPathXmlApplicationContext("SpringHelloWorld.xml");
        Spring3HelloWorld myBean= (Spring3HelloWorld) context.getBean("Spring3HelloWorldBean");
        myBean.sayHello();
    }
}

6) Data format used in restful. – json,text plain etc.
7) What is Db deadlock
Ans:

 In a database, a deadlock is a situation in which two or more transactions are waiting for one another to give up locks. For example, Transaction A might hold a lock on some rows in the Accounts table and needs to update some rows in the Orders table to finish.



8) Restful and soap difference.
Ans:


No.
SOAP
REST
1)
SOAP is a protocol.
REST is an architectural style.
2)
SOAP stands for Simple Object Access Protocol.
REST stands for REpresentational State Transfer.
3)
SOAP can't use REST because it is a protocol.
REST can use SOAP web services   because it is a concept
and can use any protocol like HTTP, SOAP.
4)
SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business logic.
5)
JAX-WS is the java API for SOAP web services.
JAX-RS is the java API for RESTful web services.
6)
SOAP defines standards to be strictly followed.
REST does not define too much standards like SOAP.
7)
SOAP requires more bandwidth and resource than REST.
REST requires less bandwidth and resource than SOAP.
8)
SOAP defines its own security.
RESTful web services inherits security measures from
 the underlying transport.
9)
SOAP permits XML data format only.
REST permits different data format such as Plain text,
HTML, XML, JSON etc.
10)
SOAP is less preferred than REST.
REST more preferred than SOAP.













































      9) Explain Cookie and request data?
     10) 
Spring security implementation:
Web.xml entries:
Spring security implementation:
applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
       
      <!-- Scan this package for all config annotations -->
<context:component-scan base-package="com.ge.aviation.scit.supplier360.rest,com.ge.aviation.scit.supplier360.model,com.ge.aviation.scit.userservice.data,com.ge.aviation.scit.supplier360.util" />
<context:annotation-config />
<security:http use-expressions="true" auto-config="false" entry-point-ref="http403EntryPoint" >
<security:intercept-url pattern="/rest/supplier/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/details/**" access="hasRole('S_PROFILE_USER')"/>
<security:intercept-url pattern="/rest/supplier/update/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/reCalculateRating/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/finalSupplierRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/finalMetricRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/metricDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/updateMetric/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplierProfile/supplierInfo/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/yellowPage/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/sprofileUserAuth/userAuth/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/GEAEPQEReport/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersNonQmReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/DSQRReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOrganizationData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedProcessCodes/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCountryData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersStateData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCityData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersZipData/**" access="hasRole('S_PROFILE_USER')" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</security:http>
   
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
        <property name="principalRequestHeader" value="SM_USER"/>
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>   
   
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService">
            <bean id="userDetailsServiceWrapper"  class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="supplierUserDetailsService"/>
</bean>
</property>
</bean>
   
<bean id="supplierUserDetailsService" class="com.ge.aviation.scit.supplier360.security.SupplierUserDetailsService">  
       <property name="emf" ref="emf"></property>
</bean>
   
   
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></bean>
<!--  tried options  -->
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
       <property name="defaultTargetUrl" value="/home.do" />
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="jpaSupplier360"/>
</bean>

<!--<jee:jndi-lookup id="emf" jndi-name="java:jboss/datasources/nmsDS"/>
  -->
 <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="emf"/>
 </bean>
</beans>
applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
        <!-- Scan this package for all config annotations -->
<context:component-scan base-package="com.ge.aviation.scit.supplier360.rest,com.ge.aviation.scit.supplier360.model,com.ge.aviation.scit.userservice.data,com.ge.aviation.scit.supplier360.util" />
    
<context:annotation-config />
      
<security:http use-expressions="true" auto-config="false" entry-point-ref="http403EntryPoint" >
       
<security:intercept-url pattern="/rest/supplier/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/details/**" access="hasRole('S_PROFILE_USER')"/>
<security:intercept-url pattern="/rest/supplier/update/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/reCalculateRating/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/finalSupplierRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/finalMetricRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/metricDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/updateMetric/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplierProfile/supplierInfo/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/yellowPage/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/sprofileUserAuth/userAuth/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/GEAEPQEReport/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersNonQmReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/DSQRReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOrganizationData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedProcessCodes/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCountryData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersStateData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCityData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersZipData/**" access="hasRole('S_PROFILE_USER')" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</security:http>

   
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
        <property name="principalRequestHeader" value="SM_USER"/>
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>
   
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>   
   
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService">
            <bean id="userDetailsServiceWrapper"  class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="supplierUserDetailsService"/>
</bean>
</property>
</bean><bean id="supplierUserDetailsService" class="com.ge.aviation.scit.supplier360.security.SupplierUserDetailsService">  
       <property name="emf" ref="emf"></property>
</bean>
   
   
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></bean>
<!--  tried options  -->
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
       <property name="defaultTargetUrl" value="/home.do" />
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="jpaSupplier360"/>
</bean>

<!--<jee:jndi-lookup id="emf" jndi-name="java:jboss/datasources/nmsDS"/>
  -->
 <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="emf"/>
 </bean>
</beans>



import java.util.LinkedList;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ge.aviation.scit.supplier360.util.LDAPAppUser;
import com.ge.aviation.scit.supplier360.util.NmsConstants;
import com.ge.aviation.scit.supplier360.util.UserSSONTSingleton;
import com.ge.aviation.scit.userservice.data.AZLdapUserDao;
import com.ge.aviation.scit.userservice.model.AZLdapUser;
@Service("SupplierUserDetailsService")
public class SupplierUserDetailsService implements UserDetailsService
{
       EntityManagerFactory emf;
       @Inject
       LDAPAppUser ldapAppUser  ;
       @Inject
       AZLdapUserDao ldapRepository  ;
       @Autowired
       public void setEmf(EntityManagerFactory emf){
              this.emf = emf;
       }
       @Override
       @Transactional(readOnly=true)
       public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException
    {
              System.out.println("Check...Inside loadUserByUsername username:"+username);
              GrantedAuthority authority[] = new GrantedAuthority[2];
       authority[0] = new GrantedAuthorityImpl("NONE_PROFILE_USER");
       authority[1] = new GrantedAuthorityImpl("NONE_PROFILE_USER");
      
       UserSSONTSingleton  userSSONTSingleton  = UserSSONTSingleton.getInstance();
      
       AZLdapUser ldapUser = ldapRepository.findBySSO(username);

       //Get this user details from database and set its roles also here
              if(ldapUser != null)
              {
                     String userId = ldapUser.getUserId();
                     //Gupendra 11202014 - added last parameter
                     userSSONTSingleton.setSSONTMap(username, userId, ldapUser.getFirstName() + " " + ldapUser.getLastName());
                     if(ldapAppUser.isValidUser(ldapUser)){
                           authority[0] = new GrantedAuthorityImpl("S_PROFILE_USER");
                     userSSONTSingleton.setSsoAppAccessMap(username, true);
                     if(isPqeRoleUser(userId)){
                            authority[1] = new GrantedAuthorityImpl("PQE");
                     }
                     //To check logged user is supplier or not
                     LinkedList<String> listSupplerIds = new LinkedList<String>();
                     boolean isSupplier = false;
                     listSupplerIds = ldapUser.getGeaeaeecsupplierid();
                     isSupplier = ldapAppUser.checkGeaeaeecsupplierid(listSupplerIds);
                     if(isSupplier)
                     {
                            userSSONTSingleton.setNtIDSupplierMap(userId,isSupplier);
                            userSSONTSingleton.setNtIDSupplierIdsMap(userId,listSupplerIds);
                     }else{
                            userSSONTSingleton.setNtIDSupplierMap(userId,isSupplier);
                     }
                    
                     }else{
                           userSSONTSingleton.setSsoAppAccessMap(username, false);      
                     }
              }
        @SuppressWarnings("deprecation")
       UserDetails user = new User(username, "password", truetruetruetrue,authority);
      return user;
    }
       private boolean isPqeRoleUser(String username){
              try{
              if(emf== null){
                     return false;
              }
              EntityManager em = emf.createEntityManager();
              if(em== null){
                     return false;
              }
              Query query = em.createNativeQuery(NmsConstants.QUERY_CHECK_USER_ELIGIBILITY);
              query.setParameter(1, username);
              query.setParameter(2, username);
              int count = ((Number) query.getSingleResult()).intValue();
                     if (count > 0) {
                           return true;
                     } else {
                           return  false;
                     }
             
              }catch (Exception e) {
                     e.printStackTrace();
                     return false;
                     // TODO: handle exception
              }
       } //end spring security

What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like Counting SemaphoreBlockingQueueConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch which we have seen in last article  What is CountDownLatch in Java and allows multiple threads to wait for each other (barrier) before proceeding. Difference between CountDownLatch and CyclicBarrier is a also very popular multi-threading interview question in Java. CyclicBarrier is a natural requirement for concurrent program because it can be used to perform final part of task once individual tasks  are completed. All threads which wait for each other to reach barrier are called parties, CyclicBarrier is initialized with number of parties to be wait and threads wait for each other by calling CyclicBarrier.await() method which is a blocking method in Java and  blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on barrier. await() is a blocking call but can be timed out orInterrupted by other thread. In this Java concurrency tutorial we will see What is CyclicBarrier in Java  and  an example of CyclicBarrier on which three Threads will wait for each other before proceeding further.

Difference between CountDownLatch and CyclicBarrier in Java
In our last article we have see how CountDownLatch can be used to implement multiple threads waiting for each other. If you look at CyclicBarrier it also the does the same thing but there is a different you can not reuse CountDownLatch once count reaches zero while you can reuse CyclicBarrier by calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is good for one time event like application start-up time and CyclicBarrier can be used to in case of recurrent event e.g. concurrently calculating solution of big problem etc. If you like to learn more about threading and concurrency in Java you can also check my post on When to use Volatile variable in Java  and How Synchronization works in Java.
CyclicBarrier in Java – Example
Now we know what is CyclicBarrier in Java and it's time to see example of CyclicBarrier in Java. Here is a simple example of CyclicBarrier in Java on which we initialize CyclicBarrier with 3 parties, means in order to cross barrier, 3 thread needs to call await() method. each thread calls await method in short duration but they don't proceed until all 3 threads reached barrier, once all thread reach barrier, barrier gets broker and each thread started there execution from that point. Its much clear with the output of following example of CyclicBarrier in Java:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate how to use CyclicBarrier in Java. CyclicBarrier is a
 * new Concurrency Utility added in Java 5 Concurrent package.
 *
 * @author Javin Paul
 */
public class CyclicBarrierExample {

    //Runnable task for each thread
    private static class Task implements 
Runnable {

        private CyclicBarrier barrier;

        public Task(CyclicBarrier barrier) {
            this.barrier = barrier;
        }
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            } catch (BrokenBarrierException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args[]) {

        //creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await()
        final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                //This task will be executed once all thread reaches barrier
                System.out.println("All parties are arrived at barrier, lets play");
            }
        });

        //starting each of thread
        Thread t1 = new Thread(new Task(cb), "Thread 1");
        Thread t2 = new Thread(new Task(cb), "Thread 2");
        Thread t3 = new Thread(new Task(cb), "Thread 3");

        t1.start();
        t2.start();
        t3.start();
   
    }
}

Output:
Thread 1 is waiting on barrier
Thread 3 is waiting on barrier
Thread 2 is waiting on barrier
All parties are arrived at barrier, lets play
Thread 3 has crossed the barrier
Thread 1 has crossed the barrier
Thread 2 has crossed the barrier


When to use CyclicBarrier in Java
Given the nature of CyclicBarrier it can be very handy to implement map reduce kind of task similar to fork-join framework of Java 7, where a big task is broker down into smaller pieces and to complete the task you need output from individual small task e.g. to count population of India you can have 4 threads which counts population from North, South, East and West and once complete they can wait for each other, When last thread completed there task, Main thread or any other thread can add result from each zone and print total population. You can use CyclicBarrier in Java :

1) To implement multi player game which can not begin until all player has joined.
2) Perform lengthy calculation by breaking it into smaller individual tasks, In general to implement Map reduce technique.

Important point of CyclicBarrier in Java
1. CyclicBarrier can perform a completion task once all thread reaches to barrier, This can be provided while creating CyclicBarrier.

2. If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier.
3. Thread will block on await() until all parties reaches to barrier, another thread interrupt or await timed out.
4. If another thread interrupt the thread which is waiting on barrier it will throw BrokernBarrierException as shown below:

java.util.concurrent.BrokenBarrierException
        at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
        at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)

5.CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException.

That's all on  What is CyclicBarrier in Java , When to use CyclicBarrier in Java and a Simple Example of How to use CyclicBarrier in Java . We have also seen difference between CountDownLatch and CyclicBarrier in Java and got some idea where we can use CyclicBarrier in Java Concurrent code.

java.util.concurrent.CountDownLatch is a concurrency construct that allows one or more threads to wait for a given set of operations to complete.
CountDownLatch is initialized with a given count. This count is decremented by calls to the countDown() method. Threads waiting for this count to reach zero can call one of theawait() methods. Calling await() blocks the thread until the count reaches zero.
Below is a simple example. After the Decrementer has called countDown() 3 times on theCountDownLatch, the waiting Waiter is released from the await() call.
CountDownLatch latch = new CountDownLatch(3);
Waiter      waiter      = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);
new Thread(waiter)     .start();
new Thread(decrementer).start();

Thread.sleep(4000);
public class Waiter implements Runnable{

    CountDownLatch latch = null;

    public Waiter(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Waiter Released");
    }
}

public class Decrementer implements Runnable {

    CountDownLatch latch = null;

    public Decrementer(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {

        try {
            Thread.sleep(1000);
            this.latch.countDown();

            Thread.sleep(1000);
            this.latch.countDown();

            Thread.sleep(1000);
            this.latch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}




No comments:

Post a Comment