Monday, 30 April 2018

Using c-namespace in Spring

While using Spring XML configuration for wiring beans you would have used <constructor-arg> element several times for providing, property values and/or providing reference for beans, as a constructor injection. If you are looking for any shorter alternative, just as p-namesapce is used in place of nested <property> element, you can use c-namespace in Spring.

The c-namespace in Spring enables you to use the bean element’s attributes for configuring the constructor arguments rather than nested constructor-arg elements.

As example –

If you have an XML configuration for bean employee which has a constructor that refers to the bean of type address with constructor-arg you will write it like this -

<bean id="employee" class="org.netjs.model.Employee">
    <constructor-arg ref="address"/>
</bean>

You can use c-namespace to shorten it like this -

<bean id="employee" class="org.netjs.model.Employee" c:officeAddress-ref="address">
    <!-- <constructor-arg ref="address"/> -->
</bean>

You can see here that instead of using nested <constructor-arg> element you can use bean element’s attribute itself.

In this way of using c-namespace for injection of bean reference c:officeAddress-ref="address", c: denotes the use of c-namespace, officeAddress is the constructor argument name with in the employee class where value is injected, -ref indicates injection of bean reference.

Using c-namespace with literals

Same way c-namespace can be used for injecting literal values.

As example

If you have an XML configuration for bean employee which has a constructor argument empName then you can provide a literal value to empName property like this –

<bean id="employee" class="org.netjs.model.Employee">
    <constructor-arg value="Ram"/>
</bean>

Using c-namespace you can shorten it like this –

<bean id="employee" class="org.netjs.model.Employee" c:empName="Ram">
    <!-- <constructor-arg value="Ram"/> -->
</bean>

Spring c-namespace example

As we have already seen there are two classes Address and Employee and Address class bean is referred in Employee.

Employee class

public class Employee {
 private int empId;
 private String empName;
 private int age;
 private Address officeAddress;
 
 public Employee(int empId, String empName, int age, Address officeAddress){
  this.empId = empId;
  this.empName = empName;
  this.age = age;
  this.officeAddress = officeAddress;
 }
 
 public Address getOfficeAddress() {
  return officeAddress;
 }
 
 public int getEmpId() {
  return empId;
 }
 
 public String getEmpName() {
  return empName;
 }
 
 public int getAge() {
  return age;
 }
}

Here it can be seen that Employee class has constructor that has some literal values as argument and one argument of type Address.

Address Class

public class Address {
 private String number; 
 private String street; 
 private String city; 
 private String state; 
 private String pinCode; 
 public String getNumber() {
  return number;
 }
 public void setNumber(String number) {
  this.number = number;
 }
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getPinCode() {
  return pinCode;
 }
 
 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }
 
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
   
    
    <bean id="address" class="org.netjs.model.Address" p:number="101" p:street="M I Road" 
            p:city="Jaipur" p:state="Rajasthan" p:pinCode="302001"> 
    </bean>
    
    <bean id="employee" class="org.netjs.model.Employee" c:empId="1001" c:age="25" 
     c:empName="Ram" c:officeAddress-ref="address" />
    
</beans>
Here notice the inclusion of xmlns:c="http://www.springframework.org/schema/c” and xmlns:p="http://www.springframework.org/schema/p” in XML configuration for c-namespace and p-namespace respectively.

In bean definition for address p-namespace is used for providing values. In bean definition for Employee c-namespace is used to provide values for constructor arguments.

Test Class

You can run this code using the following code -

import org.netjs.model.Address;
import org.netjs.model.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {        
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
         ("appcontext.xml");
        Employee emp = (Employee)context.getBean("employee");  
        Address addr = emp.getOfficeAddress();
        System.out.println("name " + emp.getEmpName());
        System.out.println("City " + addr.getCity());
        System.out.println("PinCode " + addr.getPinCode());
        context.close();    
    }
}

Output

name Ram
City Jaipur
PinCode 302001 

That's all for this topic Using c-namespace in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Using p-namespace For Shorter XML in Spring
  2. Bean Definition Inheritance in Spring
  3. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  4. Lazy Initializing Spring Beans
  5. Using Conditional annotation in Spring framework

You may also like -

  1. Using Spring profiles to switch environment
  2. Select query using JDBCTemplate in Spring framework
  3. How to read properties file in Spring Framework
  4. Functional interface annotation in Java 8
  5. Java Stream API Examples
  6. Converting string to bytearray - Java Program
  7. interface default methods in Java 8
  8. super in Java

Convert Date And Time Between Different Time-Zones in Java

You may come across a scenario where you need to convert date & time between different time zones in Java.

As example- In a flight application if you need to derive the arrival time of the flight in a different time zone.

In this post we’ll see how it can be done using the new Data and Time API in Java (Java 8 onward) which has classes like ZoneId and ZonedDateTime for that purpose.

If you are using Java 6 or 7 you can have a look at ThreeTen Backport http://www.threeten.org/threetenbp/ which provides a backport of the Java SE 8 date-time classes to Java SE 6 and 7.

Converting date & time between different time zones Java Example

For this example, I am taking a scenario where flight departs from NewArk (USA) and arrives at New Delhi (India). Departure time is 14:15 PM and date is Aug 28th, 2017. Total flight time is 19 Hrs. 25 Minutes. Using that information, you need to get the arrival time in New Delhi.

If you go by total flight time and the departure time then the arrival time would be 09:40 AM on Aug 29th, 2017. But you’ll need to consider the time zone and time difference between these zones too.

Steps for converting date and time between different time zones are as follows-

  • Create Zone Ids for the two time-zones.
  • Then create a LocalDateTime object with the departure date and time information.
  • Using that create a ZonedDateTime for the departing ZoneId.
  • Then get the ZonedDateTime for the arriving ZoneID for the same instant (New_York) in the different time-zone. This gives you the departure time in the arriving ZoneId (Delhi).
  • Now just add the total flight time to it in order to get the arrival time.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDate {

 public static void main(String[] args) {
  //Getting zone Ids
  ZoneId newArk = ZoneId.of("America/New_York");
  ZoneId delhi = ZoneId.of("Asia/Kolkata");
  
  LocalDateTime dateTime = LocalDateTime.of(2017, 8, 28, 14, 15);
  System.out.println("Date time " + dateTime);

  ZonedDateTime newArkDateTime = ZonedDateTime.of(dateTime, newArk);
  System.out.println("Date time - NewArk " + newArkDateTime);
  
  // Getting same time in different time zone
  ZonedDateTime delhiDateTime = newArkDateTime.withZoneSameInstant(delhi);
  System.out.println("Date time - India " + delhiDateTime);
   
  // Total flight time - 19 Hrs. 25 Mins. converted to mins.
  ZonedDateTime arrivalTime = delhiDateTime.plusMinutes(1165);
  
  System.out.println("Arrival Date time - Delhi " + arrivalTime);
 }
}

Output

Date time 2017-08-28T14:15
Date time - NewArk 2017-08-28T14:15-04:00[America/New_York]
Date time - India 2017-08-28T23:45+05:30[Asia/Kolkata]
Arrival Date time - Delhi 2017-08-29T19:10+05:30[Asia/Kolkata]

Converting date between different time zones- Day light saving consideration

The above code will take care of the day light saving too. You can change the month to November to verify (Day light saving ends on November 5).

LocalDateTime dateTime = LocalDateTime.of(2017, 11, 28, 14, 15);

With that date if we execute the code output is –

Output

Date time 2017-11-28T14:15
Date time - NewArk 2017-11-28T14:15-05:00[America/New_York]
Date time - India 2017-11-29T00:45+05:30[Asia/Kolkata]
Arrival Date time - Delhi 2017-11-29T20:10+05:30[Asia/Kolkata]

You can see the one hour difference in arrival now as day light saving is not observed in India.

That's all for this topic Convert Date And Time Between Different Time-Zones in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to convert Date to String in Java
  3. Converting int to string - Java Program
  4. How to Format Time in AM-PM Format - Java Program
  5. Difference Between Two Dates - Java Program

You may also like -

  1. Converting String to Enum Type - Java Program
  2. How to Find First Non-Repeated Character in a Given String - Java Program
  3. Insert\Update using NamedParameterJDBCTemplate in Spring framework
  4. Spliterator in Java
  5. PermGen Space Removal in Java 8
  6. How HashSet works internally in Java
  7. static import in Java
  8. Exception Propagation in Java Exception Handling

Sunday, 29 April 2018

Using util-namespace For Wiring Collection in Spring

Spring provides util-namespace that helps in dealing with common utility configuration issues, such as configuring collections, referencing constants. Mostly I use it for wiring collection and this post will show how to do that using util namespace in Spring.

To use the tags in the util schema, you need to declare the util-namespace and its schema in the XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans.xsd
http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/springutil.xsd"> 
<!-- bean definitions here -->
</beans>

Using util:list and util:set

Let’s take an example class Order which has a list called itemList and set called itemSet.

Order class

public class Order {
    private String id;
    private List<String> itemList;
    private Set<String> itemSet;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<String> getItemList() {
        return itemList;
    }
    public void setItemList(List<String> itemList) {
        this.itemList = itemList;
    }
    public Set<String> getItemSet() {
        return itemSet;
    }
    public void setItemSet(Set<String> itemSet) {
        this.itemSet = itemSet;
    }   
}

In order to wire this list and set with in the order bean you can have property element like this -

<bean id="orderBean" class="org.netjs.exp.Spring_Example.Order">
        <property name="id" value = "1" />
        <property name="itemList">
            <list>
                <value>Laptop</value>
                <value>RAM</value>
                <value>Drive</value>
                <value>Drive</value>
            </list>
        </property>
        <property name="itemSet">
            <set>
                <value>Laptop</value>
                <value>RAM</value>
                <value>Drive</value>
                <value>Drive</value>
            </set>
            
        </property>
 </bean>

Using util:list (and util:set) you can create a separate bean for the list or set and then wire it as a reference in the required bean.

You can also explicitly control the exact type of List that will be instantiated and populated via the use of the list-class attribute on the <util:list/> element. For set the same attribute is called set-class.

XML configuration with util:list and util:set

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">
    
    
    <util:list id="itemList" list-class="java.util.ArrayList">
        <value>Laptop</value>
        <value>RAM</value>
        <value>Drive</value>
        <value>Drive</value>
    </util:list>
    
    <util:set id="itemSet" set-class="java.util.TreeSet">
        <value>Laptop</value>
        <value>RAM</value>
        <value>Drive</value>
        <value>Drive</value>
    </util:set>
  
  <bean id="orderBean" class="org.netjs.exp.Spring_Example.Order">
      <property name="id" value = "1" />
      <property name="itemList" ref="itemList" />
      <property name="itemSet" ref="itemSet" />
  </bean>
  
</beans>

Output

item from List - Laptop
item from List - RAM
item from List - Drive
item from List - Drive
item from set - Drive
item from set - Laptop
item from set – RAM

Here you can see that list and set both are created as a separate beans now using util:list and util:set respectively. Also notice the use of list-class which is ArrayList and set-class which is given as TreeSet, that is why values in the set are sorted. Since Set can store only unique values “Drive” is stored only once even if it is specified twice for Set.

Using util:map and util:properties

In the example for util:map apart from Order class, Item class is also used.

Order class

Let’s say there is an Order class that has a Map and Properties fields.

import java.util.Map;
import java.util.Properties;

public class Order {
    private String id;
    private Map<String, Item> itemMap;
    private Properties itemProp;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Map<String, Item> getItemMap() {
        return itemMap;
    }
    public void setItemMap(Map<String, Item> itemMap) {
        this.itemMap = itemMap;
    }
    public Properties getItemProp() {
        return itemProp;
    }
    public void setItemProp(Properties itemProp) {
        this.itemProp = itemProp;
    }  
}

Item Class

public class Item {
 private String name;
 private double price;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">    
    
    <util:map id="itemMap" key-type="java.lang.String" 
     value-type="org.netjs.exp.Spring_Example.Item" map-class="java.util.HashMap">
         <entry key="1">
             <bean class="org.netjs.exp.Spring_Example.Item" p:name="RAM" 
              p:price="34.78" />
         </entry>
          <entry key="2">
             <bean class="org.netjs.exp.Spring_Example.Item" p:name="Laptop" p:price="534.00" />
         </entry>
    </util:map>
    
    <util:properties id="itemProperties" value-type="java.lang.String">
        <prop key="Laptop">500</prop>
        <prop key="RAM">56.89</prop>
    </util:properties>
    
  <bean id="orderBean" class="org.netjs.exp.Spring_Example.Order">
      <property name="id" value = "1" />
      <property name="itemMap" ref="itemMap" />
      <property name="itemProp" ref="itemProperties" />
  </bean>
  
</beans>

Output

item from Map - 1 RAM 34.78
item from Map - 2 Laptop 534.0
items from Properties {Laptop=500, RAM=56.89}

Here you can notice how map and properties are configured using util:map and util:properties respectively. In util:map notice the use of map:class attribute to define the type of Map used, key-type and value-type attributes are also used to define the type of map keys and values. While defining the values of Map, which are of type Item, p-namespace is used.

Recommendations for learning

  1. Spring Framework Master Class Course
  2. Spring & Hibernate for Beginners (Includes Spring Boot)
  3. Java In-Depth: Become a Complete Java Engineer!
  4. Complete Python Bootcamp Course
  5. React - The Complete Guide Course

That's all for this topic Using util-namespace For Wiring Collection in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Using p-namespace For Shorter XML in Spring
  2. Using c-namespace in Spring
  3. Difference Between component-scan And annotation-config in Spring
  4. Dependency Injection Using factory-method in Spring
  5. Data Access in Spring Framework

You may also like -

  1. @Required Annotation in Spring Framework
  2. @Resource Annotation in Spring Autowiring
  3. Difference Between CountDownLatch And CyclicBarrier in Java
  4. Stream API in Java 8
  5. How to find all the permutations of the given String
  6. Running Dos/Windows commands from Java program
  7. Difference between Encapsulation and Abstraction in Java
  8. Ternary operator in Java

If Given String Subsequence of Another String - Java Program

I recently remembered one interview 6-7 years back where I was asked to write a Java program to find if given string is the subsequence of another string. I started writing the program but my approach was wrong as I was getting confused between subsequence and substring.

What I wrote was to ensure that given string is the substring of another string as my assumption was that the characters should come continuously. As example if I have to find "net" exists in "netjs", then it is true as all the characters n, e, t are coming continuously in netjs.

But that’s not what subsequence means so before writing the program to ensure that given string is the subsequence of another string first let’s have a proper definition of what subsequence means.

What is a subsequence

A subsequence is a sequence where all the characters of the subsequence are present in another sequence, are in order but may not be continuous. As example – If our subsequence is “net” and we have to find if that subsequence exists in the string “npeght” then it should return true as all the characters of the subsequence (n, e, t) are present in the given string and characters are in the same order. If we delete the extra elements in the second string (p, g, h) then we get the same string.

Approach for the Java program

We can have both iterative and recursive logic for the program to find if given string is the subsequence of another string. Approach remains same for both if we have to find that String-1 is subsequence of String-2 then we start from one end of the string, it can be leftmost or rightmost (In the program here I started from the leftmost character of the strings). If character of String-1 is found in String-2 then we increment the index by 1 for both strings, if character of String-1 is not found in String-2 then we increment the index by 1 only for String-2.

Java program to find if given string is the subsequence of another string

This code has both iterative and recursive solutions.

  • Method isStringSequenceFound(String str1, String str2, int i, int j)is for recursive solution.
  • Method isStringSequenceFound(String str1, String str2) is for iterative solution.
public class SubSequenceFinder {

 public static void main(String[] args) {
        // Iterative method call
        String str1 = "abc";
        String str2 = "asc";
        boolean flag = isStringSequenceFound(str1, str2);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
        
        // Recursive method call
        str1 = "java";
        str2 = "javelina";
        flag = isStringSequenceFound(str1, str2, 0, 0);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
        
        // Iterative method call
        str1 = "abc";
        str2 = "asbbdfc";
        flag = isStringSequenceFound(str1, str2);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);

 }
 
 // Recursive method to find sub-sequence
 static boolean isStringSequenceFound(String str1, String str2, int i, int j){
  // Exit condition - if i becomes equal to length 
  // of string-1 that means all the characters are found in the second string
  if(str1.length() == i){
   return true;
  }
  //if length of String-2 becomes equal to j that means string 2 is completely
  // traversed and all the characters of string-1 are not found
  if(str2.length() == j){
   System.out.println();
   return false;
  }
  //
  if(str1.charAt(i) == str2.charAt(j)){
   // increase both i and j by 1, if char is found
   return isStringSequenceFound(str1, str2, ++i, ++j);
  }else{
   return isStringSequenceFound(str1, str2, i, ++j);
  }
 }
 
 // iterative method to find sub-sequence
 static boolean isStringSequenceFound(String str1, String str2){
  int j = 0;
  for(int i = 0; i < str2.length(); i++){
   if(str1.charAt(j) == str2.charAt(i)){
    ++j;
   }
   // All the characters of String-1 are found in String-2
   if(j == str1.length()){
    return true;
   }
  }
  // If it comes here that means all the characters of String-1
  // are not found in string-2
  return false;
 }

}

Output

abc is subsequence of asc - false
java is subsequence of javelina - true
abc is subsequence of asbbdfc - true

That's all for this topic If Given String Subsequence of Another String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Total Number of Times Each Character Appears in a String - Java Program
  2. Check Whether Given String/Number is a Palindrome or Not
  3. How to Find All The Permutations of The Given String
  4. How to Reverse a String in Java
  5. Lambda Expression Callable example

You may also like -

  1. How to convert String to Date in Java
  2. Reading all files in a folder - Java Program
  3. Ternary operator in Java
  4. String and thread-safety in Java
  5. Stream API in Java 8
  6. How ArrayList works internally in Java
  7. Object Cloning in Java
  8. What is Dependency Injection in Spring

Friday, 27 April 2018

How to Create Immutable Class in Java

Immutable class, as the name suggests, is a class whose object can’t be modified in anyway once created. Once an object of the immutable class is created and initialized the content of any field of that object can’t be changed in anyway and remains same throughout the life of the object. If there are methods that modify the content in some way then a new object is created with the modified content and returned, original object does not change.

As example String in Java is an immutable class though there are methods with in String class like substring or replace which modify the created String object. You can see in the code of the String class that for all these type of methods a new string is created with the modified data and returned. Other examples of immutable classes in Java are all the wrapper classes for primitive types like Integer, Long etc. BigDecimal and BigInteger are also immutable classes.

How to create an immutable class in Java

There are certain steps that are to be followed for creating an immutable class in Java–

  1. Methods of the class should not be overridden by the subclasses. You can ensure that by making your class final.

  2. Make all fields final and private. Marking fields as final ensures that their value is not changed. If the field is of primitive type, then it’s value can’t be changed as it is final. If field is holding a reference to another object, then declaring that field as final means its reference can’t be changed.
    Having access modifier as private for the fields ensure that fields are not accessed outside the class.

  3. Initialize all the fields in a constructor.

  4. Don’t provide setter methods or any method that can change the state of the object. Only provide methods that can access the value (like getters).

  5. In case any of the fields of the class holds reference to a mutable object any change to those objects should also not be allowed, for that –
    • Make sure that there are no methods with in the class that can change those mutable objects (change any of the field content).
    • Don’t share reference of the mutable object, if any of the methods of your class return the reference of the mutable object then its content can be changed.
    • If reference must be returned create copies of your internal mutable objects and return those copies rather than the original object. The copy you are creating of the internal mutable object must be a deep copy not a shallow copy.

In case you are wondering why such elaborate procedure for the fields holding references when fields are already final and references can’t be changed. Remember that even if reference cannot be changed you can still change the content of the fields with in a mutable object which goes against what you want to achieve by making your class immutable.

Creating Immutable class Java example

In the example there are two classes. Address class is the mutable class whose object is there in the immutable class ImmutableEmployee.

Address.java

public class Address {
 private String addressLine1;
 private String addressLine2;
 private String city;
 public String getAddressLine1() {
  return addressLine1;
 }
 public void setAddressLine1(String addressLine1) {
  this.addressLine1 = addressLine1;
 }
 public String getAddressLine2() {
  return addressLine2;
 }
 public void setAddressLine2(String addressLine2) {
  this.addressLine2 = addressLine2;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String toString() {
  return "AddressLine1 " + addressLine1 + " AddressLine2 " + addressLine2 + " City " + city;
 }
}

ImmutableEmployee

public class ImmutableEmployee {
 private final String name;
 private final int age;
 private final Address empAddress;
 ImmutableEmployee(String name, int age, String add1, String add2, String city){
  this.name = name;
  this.age = age;
  // don't pass reference around create a new object with in constructor
  empAddress = new Address();
  empAddress.setAddressLine1(add1);
  empAddress.setAddressLine2(add2);
  empAddress.setCity(city);
 }
 
 public String getName() {
  return name;
 }
 public int getAge() {
  return age;
 }
 
 public Address getEmpAddress() {
  // creating copy of the mutable object for returning
  Address adr = new Address();
  adr.setAddressLine1(empAddress.getAddressLine1());
  adr.setAddressLine2(empAddress.getAddressLine2());
  adr.setCity(empAddress.getCity());
  return adr;
  /*return empAddress;*/
 }
 
 public String toString() {
  return "Name " + name + " Age " + age + " Address " + empAddress;
 }

 public static void main(String[] args) {
  ImmutableEmployee ie = new ImmutableEmployee("Jack", 32, "34, Hunter's Glen", "Pine Street", "Brooklyn");
  System.out.println("Employee information " + ie);
  Address adr = ie.getEmpAddress();
  adr.setCity("London");
  System.out.println("Employee information " + ie);
 }

}

Output

Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn
Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn

Here notice that in the line Address adr = ie.getEmpAddress(); I get the address object and change the city in the object but that change is not reflected in the Employee object because getEmpAddress() method creates and returns a new Address object.

You can change that method to return the original Address object, in that case your getEmpAddress() method will look like this –

 public Address getEmpAddress() {
  /*Address adr = new Address();
  adr.setAddressLine1(empAddress.getAddressLine1());
  adr.setAddressLine2(empAddress.getAddressLine2());
  adr.setCity(empAddress.getCity());
  return adr;*/
  return empAddress;
 }

Now if you execute the code and see the output -

Output

Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn
Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City London

You can see that Employee information is changed, you are now able to change the content of the Employee class object which should not be happening as it’s an immutable class. That’s why the point as mentioned above “If reference must be returned create copies of your internal mutable objects and return those copies rather than the original object.” is important.

If your class has any mutable object or using any of the modifiable collections like ArrayList, HashSet, HashMap same steps are to be followed.

Advantages of using immutable class

  1. One of the advantage of an immutable class is it is thread safe and its object can be shared among many threads without any fear of content of the original object getting changed. Refer String and thread safety to have more clarity on this point.

  2. Another advantage is you can cache immutable class objects as you know content won’t change once the object is created so no fear of dirty read. This ability to cache and reuse reduces overhead.

  3. If you ever wondered why do you see mostly String as a key for HashMap, yes, it is mostly because of String being immutable. So, if you are somehow required to use your own custom object as key and want to make sure that the object is not changed by any means (like any other thread) making that class immutable will be an option.

Disadvantages of using immutable class

  1. If the second point in the advantages of using immutable class has impressed you to make as many immutable classes in your Java application as possible just take a pause and think of the disadvantage too. Any get method where you are supposed to return the immutable class object or any field that holds a reference to a mutable object you do need to create a new object every time, copy the content from the original object and then return it. Which results in creation of many new objects and performing deep copies which again is expensive.

That's all for this topic How to Create Immutable Class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. How to create deadlock in Java multi-threading - Java Program
  2. Print odd-even numbers using threads and wait-notify
  3. How to remove duplicate elements from an array - Java Program
  4. String and thread-safety in Java
  5. String comparison in Java

You may also like -

  1. ReentrantLock in Java concurrency
  2. Difference between HashMap and ConcurrentHashMap in Java
  3. Invoking getters and setters using Reflection - Java Program
  4. Stream API in Java 8
  5. Serialization Proxy Pattern in Java
  6. Nested class and Inner class in Java
  7. Ternary operator in Java
  8. Type Casting in Java

How to Inject Prototype Scoped Bean into a Singleton Bean in Spring

In this post we'll see different ways of injecting prototype scoped bean into singleton scoped bean in Spring so that new instance of prototype scoped bean is created every time.

Problem with injecting prototype scoped bean into singleton scoped bean

If we go by the definition of the singleton and prototype beans, it says-

  • Singleton scope- Only one shared instance of a singleton bean is managed by the container, and all requests for beans with an id matching that bean definition result in that one specific bean instance being returned by the Spring container.
  • Prototype Scope- Prototype scope for a bean results in the creation of a new bean instance every time a request for that specific bean is made.

Now we are confronted with a situation when we want to inject a prototype scoped bean into a singleton scoped bean in Spring. Since dependencies are resolved at instantiation time which means if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean.

The prototype instance is the sole instance that is ever supplied to the singleton scoped bean. You cannot dependency-inject a prototype-scoped bean (new instance of bean every time) into your singleton bean, because that dependency injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.

But that's not what you want, you have given a bean prototype scope with an intention that new instance of it should be created every time.

So let's see the problem first with some code. Let's say you have two classes RequestManager and RequestHandler. RequestManager is configured as a singleton bean where as RequestHandler is defined with a prototype scope.

<bean id="requestManager" class="org.netjs.prog.RequestManager">
       <property name="requestHandler" ref="requestHandler" ></property>
</bean>
  
<bean id="requestHandler" class="org.netjs.prog.RequestHandler" scope="prototype">

</bean>

RequestManager Class

public class RequestManager {
 private RequestHandler requestHandler;
 
 public void handleRequest(){
  requestHandler.handleRequest();
 }

 public RequestHandler getRequestHandler() {
  return requestHandler;
 }

 public void setRequestHandler(RequestHandler requestHandler) {
  this.requestHandler = requestHandler;
 }
}

RequestHandler Class

public class RequestHandler {
 RequestHandler(){
  System.out.println("In Request Handler Constructor");
 }
 public void handleRequest(){
  System.out.println("Handling request");
 }
}

Now if you run this code, using this class -

public class App {
    public static void main( String[] args ){  
    
      ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
                                             ("appcontext.xml");
      RequestManager bean = (RequestManager) context.getBean("requestManager");
      // calling method three times
      bean.handleRequest();
      bean.handleRequest();
      bean.handleRequest();
      context.close();
    }
}

Output

In Request Handler Constructor
Handling request
Handling request
Handling request

Here, though method is called thrice, constructor is called only once which means RequestHandler instance is created only once.

Solutions for injecting prototype scoped bean into singleton scoped bean

There are 3 solutions to ensure that a new instance is created every time when prototype scoped bean is injected into a singleton scoped bean.

  1. Implementing the ApplicationContextAware interface
  2. Lookup method injection in Spring
  3. aop:scoped-proxy

Implementing the ApplicationContextAware interface

One solution is to implement the ApplicationContextAware interface and use the application context reference to get the bean with in the code. In that case RequestManager class will look like this. Note that according to the Spring docs this is not a good solution because the business code is aware of and coupled to the Spring Framework (look at the imports in the code). So if you want you can safely skip to the "Lookup method injection" solution.

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class RequestManager implements ApplicationContextAware{
 private RequestHandler requestHandler;
 private ApplicationContext applicationContext;
 public void handleRequest(){
  requestHandler = getRequestHandler();
  requestHandler.handleRequest();
 }
 // method to return new instance
 public RequestHandler getRequestHandler() {
  return applicationContext.getBean("requestHandler", RequestHandler.class);
  //return requestHandler;
 }

 /*public void setRequestHandler(RequestHandler requestHandler) {
  this.requestHandler = requestHandler;
 }*/

 @Override
 public void setApplicationContext(ApplicationContext applicationContext)
   throws BeansException {
  this.applicationContext = applicationContext; 
 }
}

And in XML configuration reference for RequestHandler will be removed from the RequestManager configuration.

<bean id="requestManager" class="org.netjs.prog.RequestManager">
       
</bean>
  
<bean id="requestHandler" class="org.netjs.prog.RequestHandler" scope="prototype">

Lookup method injection to inject prototype scoped bean

Lookup method injection is another way to inject prototype scoped bean into a singleton bean in Spring. You can define a look up method in your bean definition using the <lookup-method> element.

Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method.

In this case the XML Configuration will look like this

<bean id="requestManager" class="org.netjs.prog.RequestManager">
       <lookup-method name="getRequestHandler" bean="requestHandler"/>
</bean>
  
<bean id="requestHandler" class="org.netjs.prog.RequestHandler" scope="prototype" />

Note that the bean which is defined with the look up method will be dynamically subclassed by the Spring framework (using CGLIB library) and this subclass will override and provide implementation for the methods which are configured as look-up method.

The dynamically generated proxy will delegate all the non-lookup methods to the original class. For the lookup methods it will use the implementation it has provided.

Since look-up method has to be implemented so it has to be either defined as abstract method or you can provide some dummy implementation.

If the method is abstract, the dynamically-generated subclass implements the method. Otherwise, the dynamically-generated subclass overrides the concrete method defined in the original class.

If you are providing a dummy implementation then your RequestManager class will look like this -

public class RequestManager{
 private RequestHandler requestHandler;
 public void handleRequest(){
  requestHandler = getRequestHandler();
  requestHandler.handleRequest();
 }
 
 // dummy implmentation, configured as look-up method
 public RequestHandler getRequestHandler() {
  return null;
 }
}

In case you are defining the method as abstract then you will have to mark the class also as abstract class. It may create problem with in your whole implementation and also make the unit-testing difficult. Anyway in case you want it to be an abstract method then the RequestManager class will look like this -

public abstract class RequestManager{
 private RequestHandler requestHandler;
 public void handleRequest(){
  requestHandler = getRequestHandler();
  requestHandler.handleRequest();
 }
 
 public abstract RequestHandler getRequestHandler(); 
}

Now if you run it using this test class -

public class App {
    public static void main( String[] args ){  
       ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
                                                ("appcontext.xml");
        RequestManager bean = (RequestManager) context.getBean("requestManager");
        bean.handleRequest();
        bean.handleRequest();
        bean.handleRequest();
        context.close();
    }
}

Output

In Request Handler Constructor
Handling request
In Request Handler Constructor
Handling request
In Request Handler Constructor
Handling request

Now you can see that three instances of RequestHandler are created for three separate calls.

Some of the points to remember when using look-up method-

  • For this dynamic subclassing to work, the class that the Spring bean container will subclass cannot be final, and the method to be overridden cannot be final either.
  • Unit-testing a class that has an abstract method requires you to subclass the class yourself and to supply a stub implementation of the abstract method.
  • Concrete methods are also necessary for component scanning which requires concrete classes to pick up.

Using aop:scoped-proxy

Third way to inject prototype scoped bean in a singleton bean is using aop scoped proxy. Though Spring docs say "You do not need to use the <aop:scoped-proxy/> in conjunction with beans that are scoped as singletons or prototypes." As it is more suitable to be used in the scenario when you are working with request, session and application scope and want to resolve the problem of how long do you want your bean to live.

As Spring docs say "you don't" not "you shouldn't" so we can anyway use it with singleton and prototype too.

When using aop scoped proxy the XML configuration will look like this -

<bean id="requestManager" class="org.netjs.prog.RequestManager">
       <property name="requestHandler" ref="requestHandler"/>
</bean>
<bean id="requestHandler" class="org.netjs.prog.RequestHandler" scope="prototype">
    <aop:scoped-proxy/>
</bean>

Note that with look up method solution it was the singleton bean which was getting proxied but with aop scoped proxy it is the prototype bean which will be proxied.

So if we take our classes as example, the container will create a proxy object of the RequestHandler which can fetch the real RequestHandler class object from the defined scoping mechanism (prototype, request, session etc.)

The container injects this proxy object into the requestManager bean, which is unaware that this requestHandler reference is a proxy.

When a RequestManager instance invokes a method on the dependency-injected RequestHandler object, it actually is invoking a method on the proxy. The proxy then fetches the real RequestHandler object and delegates the method invocation onto the retrieved real RequestHandler object.

There are 2 ways to create proxy class using aop scoped proxy.

  1. Using CGLIB library, this is the default option.
  2. Using JDK interface-based proxies for such scoped beans, by specifying false for the value of the proxy-target-class attribute of the <aop:scoped-proxy/> <aop:scoped-proxy proxy-target-class="false" />

RequestManager Class when using aop scoped proxy

public class RequestManager{
 private RequestHandler requestHandler;
 public void handleRequest(){
  requestHandler.handleRequest();
 }
 public RequestHandler getRequestHandler() {
  return requestHandler;
 }
 public void setRequestHandler(RequestHandler requestHandler) {
  this.requestHandler = requestHandler;
 }
}

RequestHandler Class

public class RequestHandler {
 RequestHandler(){
  System.out.println("In Request Handler Constructor");
 }
 public void handleRequest(){
  System.out.println("Handling request");
 }
}

Output

In Request Handler Constructor
Handling request
In Request Handler Constructor
Handling request
In Request Handler Constructor
Handling request

That's all for this topic How to Inject Prototype Scoped Bean into a Singleton Bean in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Injecting Inner Bean in Spring
  2. Lazy Initializing Spring Beans
  3. Different bean scopes in Spring
  4. Wiring collections in Spring
  5. Using Conditional Annotation in Spring Framework

You may also like -

  1. Spring example program using XML configuration
  2. Insert\Update Using JDBCTemplate in Spring Framework
  3. Difference Between component-scan And annotation-config in Spring
  4. How HashMap internally works in Java
  5. static import in Java
  6. interface static methods in Java 8
  7. Java Multi-threading interview questions
  8. Method reference in Java 8

Data Access in Spring Framework

This Spring data access tutorial provides basics about the DB access through Spring framework like how Spring abstracts the data access, how you can use templates for data access, Spring’s data access exception handling.

If you have to describe how data access is handled by Spring Framework using 2 keywords then those 2 words will be-

  • Abstraction
  • Agnostic

Now JDBC or any ORM framework do provide abstraction of its own and you use JDBC or ORM as an abstract layer to interact with DB then what abstraction does spring provide?

Again two keywords are -

  • Template
  • Exception Handling

Before delving any further into those keywords let’s talk about the “agnostic” feature too (which will cover the Exception handling point too!). It is said that data access exception handling in Spring framework is platform agnostic. What does that mean?

Spring’s data access exception handling is platform agnostic

If you have used JDBC you must be knowing that it forces you to catch SQLException. SQLExcpetion is an exception that provides information on a database access error or other errors some of the scenarios when SQLException can be thrown are -

  • The application is not able to connect to the DB.
  • SQL Query which has to be executed is not correct syntactically.

But the question here is by catching SQLException you can’t do much anyway. Also the SQLExcpetion hierarchy is not very rich. Though it does provide a String describing the error and an integer error code that is specific to each vendor which is helpful in knowing about the error.

Coming to Spring framework it provides data access mechanism for getting data through JDBC, various ORM frameworks like Hibernate, Ibatis. Now think of a situation where Spring provides the layer over the JDBC or any ORM framework but doesn’t provide any mechanism to handle exceptions thrown by them. In that case your code will become a hotchpotch of Spring templates and then exception handling by JDBC, Hibernate, Ibatis or any other way of data access.

That’s where Spring’s platform agnostic exception handling comes to the rescue.

For JDBC org.springframework.jdbc.support package provides SQLException translation functionality and some utility classes. Exceptions thrown during JDBC processing are translated to exceptions defined in the org.springframework.dao package. This means that code using the Spring JDBC abstraction layer does not need to implement JDBC or RDBMS-specific error handling.

All translated exceptions are unchecked exceptions, which gives you the option of catching the exceptions from which you can recover while allowing other exceptions to be propagated to the caller.

Same way implementations of PersistenceExceptionTranslator interface in Spring provides exception translation for data access technologies that throw runtime exceptions, such as JPA, TopLink, JDO and Hibernate.

Using these translator classes Spring translates the platform specific exception to the Spring specific exception under the hood, so you are abstracted from how it is done.

Some of the advantages of the exception handling mechanism followed by Spring are -

  1. Non-intrusive – Since data access exceptions thrown by Spring are not checked exceptions so user is not forced to handle it or declare it. That way you are not making your application tightly coupled with the Spring APIs.
  2. Catch Late - In case of checked exceptions, it is enforced by Java compiler to either catch the exception or declare it in throws clause. So generally developer tends to catch it and do nothing except printing stacktrace or put a logger in order to avoid the compiler error. But that way we are not providing the true information of what exactly happened. It is better to catch exception only when it can be handled appropriately. Since Spring's data access exceptions are unchecked exceptions theses exceptions can be thrown up the call hierarchy, without the botheration of declaring with throws clause or rethrowing them, and the best place in the hierarchy can handle it more effectively.

Spring data access Exception Hierarchy

Spring’s exception hierarchy is quite rich and the main thing is that it can be used with any persistence solution. Whatever persistence solution you are using, if exception is thrown Spring framework will translate it and throw a consistent set of exceptions.

Parent class in Spring's exception hierarchy is DataAccessException and important point about is that it is an unchecked exception. So, you are not forced to catch Spring's data access exceptions, though you can catch them if you want.

In fact the convention is that you should not handle any exceptions in the DAO layer, instead throw it to the front-end and handle it.

Some of the sub classes of the DataAccessException class are – BadSqlGrammarException, DuplicateKeyException, EmptyResultDataAccessException, CannotGetJdbcConnectionException, QueryTimeoutException.

There are many more if you want to go through the whole list plase refer Spring reference doc.

In order to take advantage of Spring’s data-access exceptions, you need to use one of the data access templates provided by Spring framework. That brings us to the point about templates.

Using Templates for Data Access in Spring

Spring provides many templates for data access (For JDBC, for Hibernate, for MongoDB and many more). If you have idea about template design pattern you can get an idea what these templates are doing.

You generally use Template design pattern if you have to design the functionality where some implementation is common among the classes and some implementation differs. So in template design pattern -

  • There is a base class with common implementations.
  • Methods that require individual implementation are mere place holder in base class.
  • Sub classes can provide implementation for those place holder methods.

So, base class provides the template of the implementation and fill what it can (common implementation) and delegates the other parts to the implementing classes.

Same process is used by the Spring data access. Whatever persistence mechanism is used there are some common steps like getting the DB connection, handling exception if thrown and cleaning up the resources (closing the connection) once done. These can be termed as fixed part.

But how and what data is accessed, what data is updated is different for different application. That can be termed as variable part.

Template classes in Spring framework provide implementation for the fixed part and uses a callback approach to handle variable part which is your custom data access code, benefit of template class is that it frees application code from having to do the boilerplate tasks like getting DB connection, handling exceptions, closing connection and results in code that is intention driven. That way the code that is written focuses solely on what the developer wants to do.

As example- JdbcTemplate class is the central class in the JDBC core package. It handles the creation and release of resources, which helps you avoid common errors such as forgetting to close the connection.
It performs the basic tasks of the core JDBC workflow such as statement creation and execution, leaving application code to provide SQL and extract results. The JdbcTemplate class executes SQL queries, update statements and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.

When you use the JdbcTemplate for your code, you only need to implement callback interfaces, giving them a clearly defined contract. The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class, providing SQL and any necessary parameters. The same is true for the CallableStatementCreator interface, which creates callable statements. The RowCallbackHandler interface extracts values from each row of a ResultSet.

Some of the templates provided by Spring framework -

  • jdbc.core.JdbcTemplate – For JDBC connections.
  • jdbc.core.namedparam.NamedParameterJdbcTemplate - For JDBC connections with named parameters.
  • orm.hibernate3.HibernateTemplate – For Hibernate 3.x sessions.
  • orm.hibernate4.HibernateTemplate - For Hibernate 4.x sessions.

In order to manage the fixed part like getting connection, releasing resources Spring template needs a reference to a DataSource. Refer Configuring DataSource in Spring Framework to see different ways to configure data source in Spring.

That's all for this topic Data Access in Spring Framework. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  2. Spring JdbcTemplate With ResultSetExtractor Example
  3. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  4. How to Inject Prototype Scoped Bean in Singleton Bean
  5. How to Read Properties File in Spring Framework

You may also like -

  1. What is Dependency Injection in Spring
  2. Autowiring using XML configuration in Spring
  3. Lazy Initializing Spring Beans
  4. Creating a Maven project in Eclipse
  5. Lambda expressions in Java 8
  6. LinkedHashMap in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Switch-Case statement in Java

LinkedBlockingDeque in Java

LinkedBlockingDeque in Java is an implementation of the BlockingDeque interface and it was added in Java 6.

LinkedBlockingDeque is an optionally bounded deque and it stores its elements as linked nodes. Since it is optionally bounded so it has constructor which takes initial capacity as parameter. In case capacity is not specified it is equal to Integer.MAX_VALUE.

Java LinkedBlockingDeque constructors

LinkedBlockingDeque in Java has three constructors-

  • LinkedBlockingDeque()- Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE.
  • LinkedBlockingDeque(Collection<? extends E> c)- Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection's iterator.
  • LinkedBlockingDeque(int capacity)- Creates a LinkedBlockingDeque with the given (fixed) capacity.

Here note that Linked nodes are dynamically created upon each insertion unless this would bring the deque above capacity. In case initial capacity is defined then the blocking method like put(E e) will wait if necessary for space to become available.

Since elements are stored as linked nodes so most of the operations like add(), addFirst(), put(), putFirst() run in constant time (ignoring time spent blocking). Exceptions include remove(object o), removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.

LinkedBlockingDeque Java Example code

Let's create a produce consumer bounded buffer using LinkedBlockingDeque which is an implmentation of BlockingDeque.

Values will be inserted in the LinkedBlockingDeque using put() method, which will block if the space is full.

Values will be retrieved from the LinkedBlockingDeque using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Here in the Produce class some delay is induced using sleep() method. You can see that in Consumer class, where it is taking elements out of the deque, no excpetion will be thrown but it will block. If you are using eclipse you can see that delay in the console when it is printing.

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDQDemo {
    public static void main(String[] args) {
        SharedClass buffer = new SharedClass();
        // Starting two threads
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Producer(buffer));
        executor.execute(new Consumer(buffer));
        executor.shutdown();

    }
}
/**
 * 
 */
class Producer implements Runnable{
    SharedClass buffer;
    Producer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.put(i);
            if(i == 4){
                try {
                    // introducing some delay using sleep
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
/**
 * 
 */
class Consumer implements Runnable{
    SharedClass buffer;
    Consumer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.get();;
        }
    }    
}

//Shared class used by threads
class SharedClass{
    int i;
    // Bounded LinkedBlockingDeque of size 10
    BlockingDeque<Integer> linkedBlockingDeque = new LinkedBlockingDeque<Integer>(10);
    
    public void get(){
       try {
            // take method to get from blockingdeque
           System.out.println("Consumer recd - " + linkedBlockingDeque.take());
       } catch (InterruptedException e) {
            // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    
    public void put(int i){
       this.i = i;
       try {
            // putting in blocking deque
            linkedBlockingDeque.put(i);
            System.out.println("Putting - " + i);
       }
       catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
       } 
    }
}

Output

Putting - 0
Putting - 1
Putting - 2
Putting - 3
Putting - 4
Consumer recd - 0
Consumer recd - 1
Consumer recd - 2
Consumer recd - 3
Consumer recd - 4
Putting - 5
Consumer recd - 5
Putting - 6
Consumer recd - 6
Putting - 7
Consumer recd - 7
Putting - 8
Consumer recd - 8
Putting - 9
Consumer recd - 9

That's all for this topic LinkedBlockingDeque in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. BlockingDeque in Java Concurrency
  2. BlockingQueue in Java Concurrency
  3. LinkedBlockingQueue in Java Concurrency
  4. Phaser in Java Concurrency
  5. Java Concurrency Interview Questions And Answers

You may also like -

  1. Race condition in Java multi-threading
  2. Why wait(), notify() and notifyAll() methods are in Object class
  3. ThreadLocal class in Java
  4. Functional Interfaces in Java
  5. Stream API in Java 8
  6. Heap Memory Allocation in Java
  7. static in Java
  8. Data Access in Spring Framework

Thursday, 26 April 2018

BlockingDeque in Java

BlockingDeque interface in Java (added in Java 6) is a Deque that provides additional support for blocking operations. Here blocking the operations means that the operation will wait for the deque to become non-empty (means deque has at least one element) when retrieving an element, and wait for space to become available in the deque when storing an element.

Deque in Java

Deque is also an interface which was added in Java 6. Deque is short for "double ended queue". As the name suggests Deque supports element insertion and removal at both ends.

Java BlockingDeque

Like any BlockingQueue, BlockingDeque in Java is thread safe, does not permit null elements, and may (or may not) be capacity-constrained.

LinkedBlockingDeque class in Java is the implementation of the BlockingDeque interface.

BlockingDeque methods in Java

As already mentioned BlockingDeque in Java provides support for the blocking operations, but blocking methods come in four forms, categorized in the way these methods will handle operations that cannot be satisfied immediately, but may be satisfied at some point in the future:

  • Throw exception- Methods falling in this category will throw exception if blocked.
  • Return special value- This type of methods will return some value if need to wait, like false.
  • Blocks- This type of methods will wait if necessary for space to become available.
  • Times out- This type of methods will block for only a given maximum time limit before giving up.

These methods are summarized in the following table:

First Element (Head)
Throws exception Special value Blocks Times out
Insert addFirst(e) offerFirst(e) putFirst(e) offerFirst(e, time, unit)
Remove removeFirst() pollFirst() takeFirst() pollFirst(time, unit)
Examine getFirst() peekFirst() not applicable not applicable
Last Element (Tail)
Throws exception Special value Blocks Times out
Insert addLast(e) offerLast(e) putLast(e) offerLast(e, time, unit)
Remove removeLast() pollLast() takeLast() pollLast(time, unit)
Examine getLast() peekLast() not applicable not applicable

BlockingDeque Java Example

Let's create a produce consumer bounded buffer using LinkedBlockingDeque which is an implmentation of BlockingDeque.

Values will be inserted in the LinkedBlockingDeque using put() method, which will block if the space is full.

Values will be retrieved from the LinkedBlockingDeque using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Here in the Produce class some delay is induced using sleep() method. You can see that in Consumer class, where it is taking elements out of the deque, no exception will be thrown but it will block. If you are using eclipse you can see that delay in the console when it is printing. Later we'll see the same example using deque which is not thread safe there it will throw an exception.

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDQDemo {
    public static void main(String[] args) {
        SharedClass buffer = new SharedClass();
        // Starting two threads
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Producer(buffer));
        executor.execute(new Consumer(buffer));
        executor.shutdown();
    }
}
/**
 * 
 */
class Producer implements Runnable{
    SharedClass buffer;
    Producer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.put(i);
            if(i == 4){
                try {
                    // introducing some delay using sleep
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * 
 */
class Consumer implements Runnable{
    SharedClass buffer;
    Consumer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.get();;
        }
    }    
}

//Shared class used by threads
class SharedClass{
    int i;
    // Bounded LinkedBlockingDeque of size 10
    BlockingDeque<Integer> linkedBlockingDeque = new LinkedBlockingDeque<Integer>(10);
    
    public void get(){
       try {
            // take method to get from blockingdeque
           System.out.println("Consumer recd - " + linkedBlockingDeque.take());
       } catch (InterruptedException e) {
            // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    
    public void put(int i){
       this.i = i;
       try {
            // putting in blocking deque
            linkedBlockingDeque.put(i);
            System.out.println("Putting - " + i);
       }
       catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
       } 
    }
}

Output

Putting - 0
Putting - 1
Putting - 2
Putting - 3
Putting - 4
Consumer recd - 0
Consumer recd - 1
Consumer recd - 2
Consumer recd - 3
Consumer recd - 4
Putting - 5
Consumer recd - 5
Putting - 6
Consumer recd - 6
Putting - 7
Consumer recd - 7
Putting - 8
Consumer recd - 8
Putting - 9
Consumer recd - 9

Now let's write the same code as above using the Deque which is not thread safe. Here one change is instead of LinkedBlockingDeque, ArrayDeque is used which is implementation of Deque and also some delay is induced in consumer class too just to make sure that producer will start first. Then producer sleeps for 1000 MS, that is when exception is thrown.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DQDemo {
    public static void main(String[] args) {
        SharedClass buffer = new SharedClass();
        // Starting two threads
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Producer(buffer));
        executor.execute(new Consumer(buffer));
        executor.shutdown();

    }
}

/**
 * 
 */
class Producer implements Runnable{
    SharedClass buffer;
    Producer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.put(i);
            if(i == 4){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * 
 */
class Consumer implements Runnable{
    SharedClass buffer;
    Consumer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i = 0; i < 10; i++){
            buffer.get();;
        }
    }    
}

//Shared class used by threads
class SharedClass{
    int i;
    // Bouded ArrayDeque of size 10
    Deque<Integer> arrayDq = new ArrayDeque<Integer>(10);
    public void get(){
        // retrieve from deque
        System.out.println("Consumer recd - " + arrayDq.pop());
    }
    
    public void put(int i){
        this.i = i;
        arrayDq.push(i);
        System.out.println("Putting - " + i);
    }
}

Output

Putting - 0
Putting - 1
Putting - 2
Putting - 3
Putting - 4
Consumer recd - 4
Consumer recd - 3
Consumer recd - 2
Consumer recd - 1
Consumer recd - 0
Exception in thread "pool-1-thread-2" java.util.NoSuchElementException
 at java.util.ArrayDeque.removeFirst(Unknown Source)
 at java.util.ArrayDeque.pop(Unknown Source)
 at org.netjs.prgrm.SharedClass.get(DQDemo.java:77)
 at org.netjs.prgrm.Consumer.run(DQDemo.java:65)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)
Putting - 5
Putting - 6
Putting - 7
Putting - 8
Putting - 9

Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/concurrent/BlockingDeque.html

That's all for this topic BlockingDeque in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. LinkedBlockingDeque in Java
  2. ArrayBlockingQueue in Java Concurrency
  3. LinkedBlockingQueue in Java Concurrency
  4. CopyOnWriteArrayList in Java
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. Race condition in Java multi-threading
  2. Inter-thread communication using wait, notify and notifyAll
  3. Why wait(), notify() and notifyAll() methods are in Object class
  4. How to remove duplicate elements from an ArrayList in Java
  5. How to Sort elements in different order in TreeSet
  6. Functional interface annotation in Java 8
  7. super in Java
  8. What is Dependency Injection in Spring