Friday, January 6, 2023

Excluding Bean From Autowiring in Spring

You can exclude a bean from autowiring in Spring framework per-bean basis. If you are using Spring XML configuration then you can exclude a bean from autowiring by setting the autowire-candidate attribute of the <bean/> element to false. That way container makes that specific bean definition unavailable to the autowiring infrastructure.

Excluding bean using autowire-candidate example

Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also there are two classes CashPayment and CardPayment which implements IPayment interface.

IpayService interface

public interface IPayService{
 void performPayment();
}

PayServiceImpl class

import org.springframework.beans.factory.annotation.Autowired;

public class PayServiceImpl implements IPayService{
 @Autowired
 private IPayment payment;
 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }

 public void performPayment() {
  System.out.println("performPayment Method called");
  payment.executePayment();
 }
}

Here note the @Autowired annotation on payment field.

Interface Ipayment

public interface IPayment{
 void executePayment();
}

CashPayment class

public class CashPayment implements IPayment{
 
 public void executePayment() {
  System.out.println("Perform Cash Payment "); 
 }
}

CardPayment class

public class CardPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Card Payment "); 
 }
}

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:context="http://www.springframework.org/schema/context"
  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">
  
  <context:annotation-config/>
   
  <bean id="cash" class="org.netjs.exp.Spring_Example.CashPayment" />
  <bean id="card" class="org.netjs.exp.Spring_Example.CardPayment" />
 
  <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl">
  </bean>
</beans>

Here we have defined two beans of type Ipayment, CashPayment and CardPayment. This will result in BeanCreationException as container won’t be able to decide which on of the two inject in PayServiceImpl class.

You can check that by running the code using the following Java class.

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

public class App {
  public static void main( String[] args ){
    AbstractApplicationContext context = new ClassPathXmlApplicationContext
       ("appcontext.xml");

    IPayService payBean = (IPayService)context.getBean("payServiceBean");
    payBean.performPayment();
    context.registerShutdownHook();
  } 
}

Output

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'payServiceBean': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.netjs.exp.Spring_Example.IPayment org.netjs.exp.Spring_Example.PayServiceImpl.payment; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.netjs.exp.Spring_Example.IPayment] is defined: expected single matching bean but found 2: cash,card

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.netjs.exp.Spring_Example.IPayment] is defined: expected single matching bean but found 2: cash,card

If you set autowire-candidate attribute as false for one of the bean then the problem will be resolved.

<bean id="cash" class="org.netjs.exp.Spring_Example.CashPayment" autowire-candidate="false" />

With this change if you run the code, card bean will be injected.

Output

performPayment Method called
Perform Card Payment 

Resolving conflict with annotations

If you want to use annotations to resolve conflict in this type of situation when you have more than one bean defined of the same type. Then you have two options.

  1. @Qualifier annotation.
  2. @Inject and @Named annotation

Using @Qualifier annotation example

In the example used above where you have two beans CardPayment and CashPayment of the same type, in order to avoid ambiguity you can use @Qualifier annotation to qualify the bean.

Suppose you want to inject cashPaymentBean then you can qualify it by passing bean name with the qualifier annotation in the PayServiceImpl class.

PayServiceImpl.java

public class PayServiceImpl implements IPayService{
 @Autowired
 @Qualifier("cash")
 private IPayment payment;
 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }

 public void performPayment() {
  System.out.println("performPayment Method called");
  payment.executePayment();
 }
}

Now even if you don’t set autowire-candidate as false for any of the bean that’s ok as @Qualifier annotation will resolve the conflict.

<bean id="cash" class="org.netjs.exp.Spring_Example.CashPayment" />
<bean id="card" class="org.netjs.exp.Spring_Example.CardPayment" />

Using @Inject and @Named annotations

If you want to make sure that CashPayment bean is the one which is injected then using @Inject and @Named annotations the PayServiceImpl class will look like-

import javax.inject.Inject;
import javax.inject.Named;

public class PayServiceImpl implements IPayService{
 @Inject
 @Named("cash")
 private IPayment payment;
 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }


 public void performPayment() {
  System.out.println("performPayment Method called");
  payment.executePayment();
 }
}

Note that you will need to import javax.inject jar in order to use these annotations. In Maven you can do it by adding the following dependency.

<dependency>
  <groupId>javax.inject</groupId>
  <artifactId>javax.inject</artifactId>
  <version>1</version>
</dependency>

Recommendations for learning (Udemy Courses)

  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 Excluding Bean From Autowiring 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. Autowiring in Spring Using XML Configuration
  2. Autowiring in Spring Using @Autowired and @Inject Annotations
  3. Benefits, Disadvantages And Limitations of Autowiring in Spring
  4. Spring MessageSource Internationalization (i18n) Support
  5. Spring Object XML Mapping (OXM) JAXB Example

You may also like-

  1. Spring depends-on Attribute and @DependsOn With Examples
  2. Bean Definition Inheritance in Spring
  3. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  4. Spring MVC @PathVariable Example - Creating Dynamic URL
  5. Java String substring() Method - Getting Substring
  6. PermGen Space Removal in Java 8
  7. Java Nested Class And Inner Class
  8. Java Multithreading Interview Questions And Answers

Thursday, January 5, 2023

Reduction Operations in Java Stream API

Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations in Java Stream API because these operations reduce the stream to a single non-stream value.

Examples of these reduction operations can be seen in the post Java Stream API Examples.

Apart from these above mentioned reduction operations, Java Stream API also provides general-purpose reduce methods that can be used with any user supplied logic to get a value from the stream.

Stream API in Java provides three versions of reduce() method-

  1. Optional<T> reduce(BinaryOperator<T> accumulator)- This reduce method returns an object of type Optional which contains the result. Notice that the result stored by Optional is of type T which also happens to be the element type of the stream.

    BinaryOperator is a functional interface which means it will have a single Abstract Method. Thus, accumulator is a function that will implement the method of the interface.
    If you see the description for BinaryOperator it says- Represents an operation upon two operands of the same type, producing a result of the same type as the operands.

    BinaryOperator extends another functional interface BiFunction which has this method-

    • R apply(T t, U u)- Applies this function to the given arguments.
    • Where R is the type of the result, T is the type of the first argument and U is the type of the second argument. (This explanation will help with the third form of the reduce method so please bear with me!).
    But in case of Binary Operator, as we have already seen in the explanation, two operands as well as the result are of same type so apply method effectively becomes T apply(T t, T u) in context of BinaryOperator.

    Here two things to note are-

    • When reduction is performed on the elements of this stream, using accumulation function (which is actually this apply method T apply(T t, Tu)) t will contain the previous result and u will contain the next element.
    • In the first invocation of this form of reduce method t will contain the first element.
  2. T reduce(T identity, BinaryOperator<T> accumulator)- This reduce method returns the result of type T which is same as the element type of the stream. The provided identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t i.e. applying the accumulation operation on the identity value and any element of the stream will give you back the element.

    For example, if the operation is addition then the identity value will be 0 as 0 + element = element, in case operation is multiplication then identity value is 1 as 1 * element = element.

  3. <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)- In the third form you can see there are three parameters where apart from identity and accumulator (which is a BiFunction, as explained above) function there is also a combiner function which is a BinaryOperator. Combiner function gives user a way to tell how partial results are to be combined. It becomes important in case parallel stream is used (we’ll see an example soon).

    Another thing you should have noticed is the return type, here it is different from the element type of the stream. In other two variants of the reduce method return type is either an object of Optional (where value stored in the Optional object is same as element type of the stream) or same as element type of the stream.

Java Stream API reduce method example

Let’s see some examples of the reduce method in Java Streams. For that lets take an Employee class where employee with maximum salary is needed as result. Using the first two variants it can be done as-

Employee class

public class Employee {
    private String lastName;
    private String firstName;
    private String empId;
    private int age;
    private int salary;
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
}

Class with reduce methods

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

public class ReduceDemo {

    public static void main(String[] args) {       
        List<Employee> empList = createList();
        
        // Using reduce method which returns Optional object
        Optional<Employee> result = empList.stream().reduce((e1, e2) -> 
          e1.getSalary() > e2.getSalary() ? e1 : e2);
        if(result.isPresent()){
            System.out.println("Employee with max salary - " + result.get().getFirstName() 
             + " salary " + result.get().getSalary());
        }
        
        // Using reduce method with identity element
        Employee emp = empList.stream().reduce(new Employee(), (e1, e2) -> 
          e1.getSalary() > e2.getSalary() ? e1 : e2);
        System.out.println("Employee with max salary - " + emp.getFirstName() 
          + " salary " + emp.getSalary());
        
    }
    
    // /Stub method to create list of employee objects
    private static List createList(){
        List<Employee> empList = new ArrayList<Employee>();
        Employee emp = new Employee();
        emp.setEmpId("E001");
        emp.setAge(40);
        emp.setFirstName("Ram");
        emp.setLastName("Chandra");
        emp.setSalary(5000);
        empList.add(emp);
        emp = new Employee();
        emp.setEmpId("E002");
        emp.setAge(35);
        emp.setFirstName("Sheila");
        emp.setLastName("Baijal");
        emp.setSalary(7000);
        empList.add(emp);
        emp = new Employee();
        emp.setEmpId("E003");
        emp.setAge(24);
        emp.setFirstName("Mukesh");
        emp.setLastName("Rishi");
        emp.setSalary(9000);
        empList.add(emp);    
        return empList;
    }
}

Output

Employee with max salary - Mukesh salary 9000
Employee with max salary - Mukesh salary 9000

Reduce method with combiner example

Here let’s see why combiner is important. If there is a list of numbers and you want to get the product of square root of all the numbers then using reduce method, where no combiner is specified, it can be done as-

public class ReduceDemo1 {
    public static void main(String[] args) {        
        List<Double> numList = Arrays.asList(9.0, 4.0, 25.0);        
        double productOfSqrRoots = numList.parallelStream().reduce(1.0, (a, b) -> a * Math.sqrt(b));
        System.out.println("" + productOfSqrRoots);                
    }
}

This will give result as 6.344227580643384 which is not correct. It is happening because not specifying a combiner means accumulator function itself will be used as combiner function too. In that case when partial results are combined the square root is done again resulting in wrong value.

Correct way will be to define a combiner function which will just multiply the partial results.

public class ReduceDemo1 {
    public static void main(String[] args) {
        List<Double> numList = Arrays.asList(9.0, 4.0, 25.0);
        double productOfSqrRoots = numList.parallelStream().reduce(1.0, (a, b) -> 
          a * Math.sqrt(b), (a,b)->a*b);
        System.out.println("" + productOfSqrRoots);        
    }
}

Output

30.0

Here note that this problem will only happen when parallel stream is used if you are using normal stream then there won’t be any partial results to combine.

public class ReduceDemo1 {
    public static void main(String[] args) {        
        List<Double> numList = Arrays.asList(9.0, 4.0, 25.0);        
        double productOfSqrRoots = numList.stream().reduce(1.0, (a, b) -> a * Math.sqrt(b));
        System.out.println("" + productOfSqrRoots);        
    }
}

Since sequential stream is used here rather than parallelStream so you will get a correct output 30.0 now.

Sum using reduce method

Using the Employee class as used above if you want the sum of all the salaries you can do that using reduce method.

int salarySum = empList.stream().reduce(0, (sum, e) -> sum + e.getSalary(), Integer::sum);
System.out.println("Sum of all salaries " + salarySum); 

Though the explicit map-reduce form is more readable and therefore should usually be preferred. Using a chain of map and reduce to do the same thing-

int salarySum1 = empList.stream().mapToInt(Employee::getSalary).reduce(0, (s1, s2) -> s1+s2);
System.out.println("Sum of all salaries " + salarySum1);

This looks more readable, you are first getting the salary of all the employees using the map method and then using reduce method summing them.

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream API Tutorial
  2. collect() Method And Collectors Class in Java Stream API
  3. Spliterator in Java
  4. Interface Static Methods in Java
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Effectively Final in Java 8
  2. Covariant Return Type in Java
  3. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  4. Blocking Methods in Java Concurrency
  5. Java ArrayBlockingQueue With Examples
  6. How to Sort an ArrayList in Descending Order in Java
  7. How HashMap Works Internally in Java
  8. Difference Between Checked And Unchecked Exceptions in Java

Wednesday, January 4, 2023

Add Double Quotes to a String Java Program

You may come across a scenario where you would want to add double quotes to a String, but Java uses double quotes while initializing a String so it won't recognize that double quotes have to be added to the String.

You should have guessed what needed to be done in case you want to display double quotes with in a String in Java. Yes you need escape character "\" to escape quotes. So let's see an example.

Displaying double quotes Java example

public class SetQuote {
  public static void main(String[] args) {
    // escaping the double quotes as quotes are
    // needed with in the String
    String value = "\"Ram\"";
    System.out.println("Value - " + value );
  }
}

Output

Value - "Ram"

Let's take another example. You have got a String and you want to enclose part of it in double quotes.

For example let's say you are reading an XML in which first line has no double quotes.

Which means you got it as-

<?xml version=1.0 encoding=UTF-8?>

but it should be

<?xml version="1.0" encoding="UTF-8"?>

That can be done by using replace method of the String and escaping double quotes.

public class SetQuote {
  public static void main(String[] args) {
    SetQuote setQuote = new SetQuote();
    setQuote.replaceQuote();
  }

  public void replaceQuote(){
    String xmlString = "<?xml version=1.0 encoding=UTF-8?>";
    xmlString = xmlString.replace("1.0", "\"1.0\"").replace("UTF-8", "\"UTF-8\"");
    System.out.println("xmlString - " + xmlString);
  }
}

Output

xmlString - <?xml version="1.0" encoding="UTF-8"?>

That's all for this topic Add Double Quotes to a 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 Number of Words in a String Java Program
  2. If Given String Sub-Sequence of Another String in Java
  3. Convert String to Byte Array Java Program
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. How to Sort ArrayList of Custom Objects in Java

You may also like-

  1. How to Read File From The Last Line in Java
  2. Marker Interface in Java
  3. How LinkedList Class Works Internally in Java
  4. Functional Interfaces in Java
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Race Condition in Java Multi-Threading
  8. Java Concurrency Interview Questions And Answers

Tuesday, January 3, 2023

Controlled and Uncontrolled Components in React

As per React documentation ( https://beta.reactjs.org/learn/sharing-state-between-components#controlled-and-uncontrolled-components), Components are of two types-

  • Controlled Component
  • Uncontrolled Component

Controlled Component in React

A component is called controlled when the data in it is passed through props rather than managed through a local state. That way parent component has the control to specify its behavior.

Uncontrolled component in React

A component having local state and no passing of data or calling of function in other component is called an uncontrolled component.

Uncontrolled components are easier to use because they require less configuration as no communication with parent is required. But they're less flexible when you want to coordinate them together.

Controlled components are maximally flexible, but they require the parent components to fully configure them with props.

Controlled Component example

In the example there is a component CitySelect which shows a dropdown to select a city. Which city is selected and what happens when you select another city is controlled through parent component (City.js) by passing props.

CitySelect.js

const options = [
    {value:'IND', label:'India'},
    {value:'USA', label:'USA'},
    {value:'AUS', label:'Australia'},
    {value:'NET', label:'Netherlands'}
]
const CitySelect = (props) => {
    const changeCityHandler = (event) => {
        const option = event.target.options[event.target.selectedIndex];
        props.onChangeHandler(option);
    }
    return(
        <div>
            <label>Select City</label>
            <select value={props.selected} onChange={changeCityHandler}>
            {options.map((option) => (
                <option key={option.value} value={option.value}>{option.label}</option>           
            ))};
            </select>
        </div>
    );
}

export default CitySelect;

Here you can see that selected value for dropdown is determined through props, when you select another city onChange event handler is triggered which ultimately calls a function in parent component through props (props.onChangeHandler(option);).

City.js

import { useState } from "react";
import CitySelect from "./CitySelect";

const City = () => {
    const [city, setCity] = useState({value:'IND', label:'India'});
    
    const getSelectedCity = (cityoption) => {
        setCity(cityoption);
    }
    return(
        <div>
            <span>Selected City- </span>{city.label}
            <hr />
            <CitySelect selected={city.value} onChangeHandler={getSelectedCity}></CitySelect>
        </div>
    );
}

export default City;

You are sending relevant data while calling <CitySelect> tag

<CitySelect selected={city.value} onChangeHandler={getSelectedCity}></CitySelect>

If you keep the state and onChange() event handler logic in CitySelect.js then it has local state and it becomes an uncontrolled component.

Controlled and Uncontrolled component in React form

In a React form if value of an input form element is controlled by React in such a way that the component that renders a form also controls what happens in that form on subsequent user input, then that component is termed as a controlled component.

In a controlled component form input element's value and its mutation is managed through state.

Controlled Component in React form example

Here is a simple form with only a single input field and a submit button.

import { useState } from "react";

const ControlledComponent = () => {
    const [name, setName] = useState('');
    const onChangeHandler = (event) => {
        setName(event.target.value);
    }
    const onSubmitHandler = (event) => {
        event.preventDefault();
        console.log('Name', name);
    }
    return (
        <form onSubmit={onSubmitHandler}>
            <label htmlFor="name">Name: </label>
            <input type="text" id="name" value={name} onChange={onChangeHandler}></input>
            <button type="submit" >Submit</button>
        </form>
    );
}

export default ControlledComponent;

Two important points that makes this component a controlled component.

  1. React does the task of managing the state of the input field meaning managing its value and its mutation. In the input field, value attribute is set to the state value which means the input’s value is always driven by the React state.
  2. There is a onChange() event handler that runs on every keystroke to update the React state. So, the mutation of the value is also captured through state.

Uncontrolled Component in React form example

In an uncontrolled component form data is handled by the DOM itself. Which means you won't be managing state and having event handlers to update the state.

In uncontrolled component you use a ref to get form values from the DOM.

import { useRef } from "react";

const UncontrolledComponent = () => {
    const nameRef = useRef();
    const onSubmitHandler = (event) => {
        event.preventDefault();
        console.log('Name ', nameRef.current.value);
    }
    return (
        <form onSubmit={onSubmitHandler}>
            <label htmlFor="name">Name: </label>
            <input type="text" id="name" ref={nameRef}></input>
            <button type="submit" >Submit</button>
        </form>
    );
}

export default UncontrolledComponent;

As you can see now useState() hook is not used. Instead useRef is used which refers the ref assigned to the ref attribute of name input.

nameRef holds the reference to HTMLElement instance of the name input in its current property. Then using value property, we can get the value of the input element.

nameRef.current.value

That's all for this topic Controlled and Uncontrolled Components in React. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. React Declarative Approach
  2. React Virtual DOM
  3. React create-react-app Project Structure
  4. JavaScript Rest Parameter

You may also like-

  1. ArrayList in Java With Examples
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Stream API Interview Questions And Answers
  4. What is Client Side Routing in Angular

Monday, January 2, 2023

@Resource Annotation in Spring Autowiring

Apart from supporting JSR-330 annotations like @Inject and @Named for autowiring, Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods.

Spring @Resource annotation

@Resource annotation in Spring takes a name attribute, and by default Spring interprets that value as the bean name to be injected. In other words, it follows by-name semantics. That's where it differs from other annotations for autowiring like @Autowired and @Inject which are equivalent to autowiring="byType" in autowiring using XML configuration file.

In case no name is provided with @Resource annotation explicitly, the default name is derived from the field name or setter method.

  • In case of a field, it takes the field name;
  • In case of a setter method, it takes the bean property name.

For example, if we take the following class then bean with name "payment" will be injected into its setter method

public class PayServiceImpl {

 private IPayCash payment;

 @Resource
 public void setPayment(IPayCash payment) {
  this.payment = payment;
 }
}

But there is also default switching with @Resource annotation, if it doesn't find the bean with the same name it will try to match using type. So if you see how it compares with the other two annotations @Autowired and @Inject in terms of ordering followed for autowiring-

@Autowired and @Inject annotations

  1. Matches by Type
  2. Restricts by Qualifiers
  3. Matches by Name

@Resource annotation in Spring

  1. Matches by Name
  2. Matches by Type
  3. Restricts by Qualifiers (ignored if match is found by name)

So you can see in case of @Autowired and @Inject switch to "byType" happens only after restricting by Qualifier. Whereas with @Resource it switches to byType if it doesn't find the bean by name.

Another difference between these two types of annotation is that @Autowired and @Inject annotations use the 'AutowiredAnnotationBeanPostProcessor' to inject dependencies. Whereas '@Resource' annotation uses the 'CommonAnnotationBeanPostProcessor' to inject dependencies.

Source : http://stackoverflow.com/questions/4093504/resource-vs-autowired

Spring @Resource annotation example

Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also class CashPayment which implements IPayment interface.

PayServiceImpl class

import javax.annotation.Resource;

public class PayServiceImpl {
 
 @Resource(name="cashPaymentBean")
 private IPayment payment;
 
 public void performPayment() {
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }
}

Here note the @Resource annotation with name attribute on the field payment.

Interface IPayment

public interface IPayment {
 void executePayment();
}

CashPayment class

public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment "); 
 }
}

XML configuration file

<?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:context="http://www.springframework.org/schema/context"
    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">
  
  <context:annotation-config />    
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.exp.Spring_Example.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl" >
  <!--     <property name="payment" ref="cashPaymentBean" /> -->
  </bean>
</beans>

Here note that the CashPayment class bean is defined with the same name "cashPaymentBean" as used in the @Resource annotation. <context:annotation-config /> tag is added which is required for autowired annotation. Also note that ref for cashPaymentBean is no longer required as a property in paymentBean (it is commented in the config).

You can use the following code to run this program -

import org.springframework.context.support.ClassPathXmlApplicationContext;

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

Switching to byType using @Resource annotation

As already mentioned @Resource annotation will switch to "byType" if it is not able to match the bean by name. You can test it by removing the "name" attribute from @Resource annotation.

@Resource
private IPayment payment;

In this case autowiring will be tried by looking for the bean named "payment". Since it is not there so it will match by type and the program will still run.

BeanNotOfRequiredTypeException when using @Resource annotation

Since @Resource annotation tries to match by Name and then by type that may result in exception in some scenarios. Let's see an example. Here we have one more interface IPayCash and field payment in class PayServiceImpl is of type IPayCash.

IPayCash interface

public interface IPayCash {
 void executePayment();
}

PayServiceImpl class

import javax.annotation.Resource;

public class PayServiceImpl {
 
 @Resource(name="cashPaymentBean")
 private IPayCash payment;
 
 
 public void performPayment() {
  payment.executePayment();
 }
 
 public IPayCash getPayment() {
  return payment;
 }
 public void setPayment(IPayCash payment) {
  this.payment = payment;
 }
}

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:context="http://www.springframework.org/schema/context"
    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">
  
  <context:annotation-config />    
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.exp.Spring_Example.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl" >
  <!--     <property name="payment" ref="cashPaymentBean" /> -->
  </bean>
</beans>

If you see here in XML configuration CashPayment bean is defined with id "cashPaymentBean" and in Class PayServiceImpl @Resource annotation also has the same name attribute @Resource(name="cashPaymentBean") so name matching will happen without any problem.

If you have noticed types are different, in XML configuration cashPaymentBean is defined as an instance of CashPayment class which is of type IPayment, whereas in PayServiceImpl payment field is of type IPayCash. Thus at run time, because of type mismatch, "BeanNotOfRequiredTypeException" is thrown.

Output

WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'payServiceBean': 
Injection of resource dependencies failed; nested exception is 
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'cashPaymentBean' 
must be of type [org.netjs.exp.Spring_Example.IPayCash], but was actually of type 
[org.netjs.exp.Spring_Example.CashPayment]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.netjs.exp.Spring_Example.App.main(App.java:10)

That's all for this topic @Resource Annotation in Spring Autowiring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Autowiring in Spring Using @Autowired and @Inject Annotations
  2. Spring Component Scan to Automatically Discover Beans
  3. Spring Component Scan Example
  4. Using Conditional Annotation in Spring Framework
  5. BeanPostProcessor in Spring Framework

You may also like-

  1. Bean Definition Inheritance in Spring
  2. Constructor-Based Dependency Injection in Spring
  3. Spring JdbcTemplate Select Query Example
  4. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  5. Lambda Expression Examples in Java
  6. How to Find Last Modified Date of a File in Java
  7. Interface Default Methods in Java
  8. Java BlockingQueue With Examples

Sunday, January 1, 2023

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.

Probliem Statement

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

In this post 4 solutions are given 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
  4. Using ObjectFactory interface

1. 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">

2. 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 implementation, 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.

Using @Lookup annotation

You can also use @Lookup annotation, here are the updated classes to use annotations.

RequestManager class

import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

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

  @Lookup
  public RequestHandler getRequestHandler() {
    return null;
  }
}

RequestHandler class

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

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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="org.netjs.prog" />
</beans>

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.

3. 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

Same thing with annotations can be done by using the classes as given below.

RequestManager

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

RequestHandler

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestHandler {
 RequestHandler(){
  System.out.println("In Request Handler Constructor");
 }
 public void handleRequest(){
  System.out.println("Handling request");
 }
}

4. Using ObjectFactory interface

There is also an ObjectFactory interface that defines a factory which returns an Object instance (shared or independent) when invoked. In this case you'll need an independent object for the prototype scoped bean so you can encapsulate a generic factory which returns a new instance of some target object on each invocation.

RequestManager

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RequestManager{
 @Autowired
 private ObjectFactory reqHandlerObjectFactory;
 
 public void handleRequest(){
  reqHandlerObjectFactory.getObject().handleRequest();
 }
}

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. Bean Scopes in Spring With Examples
  4. Wiring collections in Spring
  5. Using Conditional Annotation in Spring Framework

You may also like-

  1. Spring XML Configuration Example
  2. Spring JdbcTemplate Insert, Update And Delete Example
  3. Difference Between component-scan And annotation-config in Spring
  4. How HashMap Works Internally in Java
  5. static Import in Java With Examples
  6. Interface Static Methods in Java
  7. Java Multithreading Interview Questions And Answers
  8. Method Reference in Java

Saturday, December 31, 2022

Java LinkedTransferQueue With Examples

LinkedTransferQueue is added in Java 7 and it is an implementation of TransferQueue interface.

TransferQueue interface in Java

It will be worthwhile to spend some time knowing the TransferQueue interface here.

TransferQueue interface, also added in Java 7, extends BlockingQueue interface. The extra functionality provided by TransferQueue interface is that it provides blocking method which will wait until other thread receives your element.

That's how it differs from BlockingQueue where you can only put element into queue or retrieve element from queue and block if queue is full (while you are putting elements) or block if queue is empty (while you are retrieving elements). So BlockingQueue won't block until consumer thread removes any particular element (Though SynchronousQueue provides that kind of functionality but more as one-to-one handoff, not as a queue.)

TransferQueue has a blocking method transfer(E e) which will ensure that the element is transferred to the consumer, it will wait if required to do so. More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in BlockingQueue.take() or timed poll), else waits until the element is received by a consumer.

TransferQueue also has put() method, just like BlockingQueue which will just enqueue the element without waiting for consumer to retrieve the element.

It also has non-blocking and time-out tryTransfer() method-

  • tryTransfer(E e)- Transfers the element to a waiting consumer immediately, if possible.
  • tryTransfer(E e, long timeout, TimeUnit unit)- Transfers the element to a consumer if it is possible to do so before the timeout elapses.

TransferQueue also has querying methods like getWaitingConsumerCount() and hasWaitingConsumer()

  • getWaitingConsumerCount()- Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll.
  • hasWaitingConsumer()- Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take() or timed poll.

Java LinkedTransferQueue

LinkedTransferQueue, as already mentioned is an implementation of the TransferQueue. LinkedTransferQueue in Java is an unbounded queue and stores elements as linked nodes.

LinkedTransferQueue orders elements FIFO (first-in-first-out) with respect to any given producer. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time for some producer.

Java LinkedTransferQueue constructors

  • LinkedTransferQueue()- Creates an initially empty LinkedTransferQueue.
  • LinkedTransferQueue(Collection<? extends E> c)- Creates a LinkedTransferQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Producer Consumer Java example using LinkedTransferQueue

Let's create a producer consumer using LinkedTransferQueue. There is a producer thread which will put elements into the queue and a consumer thread which will retrieve elements from the queue. Also a shared class which will be used by both producer and consumer threads.

To show the functionality of transfer() method delay is induced in consumer thread, since elements are stored using transfer() method so the producer will wait unless until consumer thread retrieves the element. Producer won't keep on adding the element to the queue even if consumer thread is sleeping it gets blocked.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

public class LinkedTQDemo {
  public static void main(String[] args) {
    // buffer class used by both threads
    SharedTQ buffer = new SharedTQ();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    // Executing producer
    executor.execute(new TProd(buffer));
    // Executing consumer
    executor.execute(new TCon(buffer));
    executor.shutdown();
  }
}


/**
 * Producer class
 */
class TProd implements Runnable{
  SharedTQ buffer;
  TProd(SharedTQ buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      buffer.put(i);
    }
  }
}

/**
 * Consumer class
 */
class TCon implements Runnable{
  SharedTQ buffer;
  TCon(SharedTQ buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      try {
        // introducing some delay using sleep
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        System.out.println("Error while putting in the queue " + e.getMessage());
      }
      buffer.get();
    }
  }    
}

//Shared class used by threads
class SharedTQ{
  int i;
  // TransferQueue
  TransferQueue<Integer> ltQueue = new LinkedTransferQueue<Integer>();
  
  public void get(){
    try {
      // take method to get from TransferQueue
      System.out.println("Consumer recd - " + ltQueue.take());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  public void put(int i){
    this.i = i;
    try {
      System.out.println("Putting - " + i);
      // putting in TransferQueue
      ltQueue.transfer(i);        
    }
    catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Output

Putting - 0
Consumer recd - 0
Putting - 1
Consumer recd - 1
Putting - 2
Consumer recd - 2
Putting - 3
Consumer recd - 3
Putting - 4
Consumer recd - 4

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


Related Topics

  1. Java ArrayBlockingQueue With Examples
  2. Java SynchronousQueue With Examples
  3. Java BlockingDeque With Examples
  4. Java Semaphore With Examples
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. ConcurrentSkipListMap in Java With Examples
  2. Lambda Expressions in Java 8
  3. Volatile Keyword in Java With Examples
  4. Multi-Catch Statement in Java Exception Handling
  5. super Keyword in Java With Examples
  6. static Method Overloading or Overriding in Java
  7. Add Double Quotes to a String Java Program
  8. Spring Bean Life Cycle