ExecutorService – An Overview

ExecutorService in Java

What is Executor Service?
Executor service is an interface, which allows us to process tasks asynchronously by threads.

Why ExecutorService over Threads?

ExecutorService has many advantages when compared with using casual threads,

ExecutorService takes care of threads creation for us and also re-uses threads. In java thread creation is expensive as it has to reserve the memory for each threads.  so with ExecutorService, we can create/manage/control life cycle of Threads. Also, ExecutorService provides us with methods like shutdown() and shutdownnow(), When closes the executorservice and will not accept anymore new tasks.

When we use callable in executors, we can get return result for the process.  invokeany() and invokeall() help us to run any or all threads at once.

How to create an ExecutorService?
These are some of the commonly used types of executorservices,

ExecutorService executorService = Executors.newFixedThreadPool(<size>);
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(<size>);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();

How to create tasks?
We can create tasks that is either Runnable or Callable. Both instances are executed by another thread. So what is the difference between Runnable and Callable tasks?

Runnable

Callable

Runnable doesn’t return a value Callable can return a value
Runnable cannot throw checked exceptions Callable can throw checked exceptions

Once we have implemented the tasks, we use ExecutorService to execute() or submit() the tasks.  What is the difference between execute() and submit()?

execute() – Return type is void
submit() – Returns future object for managing the tasks.

Future Object:

Using Future object we can get the status of callable tasks.  Future.get() method can wait till the callable task is finished and will return the result

invokeAll() – Executes the given tasks, returning a list of Futures holding their status and results when all complete.

invokeAny() – Executes the given tasks, returning the result of one that has completed successfully, without exception.

Shutdown() – Shutdowns the ExecutorService after completing all the submitted tasks and will not accept any new tasks.

ShutdownNow() – Stops all the executing tasks and returns the list of tasks waiting for execution.

We have covered basics of ExecutorService.

 

Read More

Generics in Java with Examples

Generics in Java with Examples

Generics allows us to pass the generic types as parameters to a class or methods.
Example: class A<T>

Generics Advantages:

  • Stronger type checking
  • Casting elimination

Type Parameter Naming Conventions:

  • E – Element
  • K – Key
  • V – Value
  • N – Number
  • T – Type

There are various ways of using Generics, In this post let us see, generics with

  • Upper Bounded Wildcards
  • Unbounded Wildcards
  • Lower Bounded Wildcards

First let us see an example of using generics along with the class

Output:

Now let us see another example of using Generics with Key and Value along with Upper Bound Wildcards, Unbounded Wildcard and Lower Bound Wildcards.

Wildcards usually starts with “?” – Example: List<? extends Number>

Upper Bound Wildcards
Used to relax restrictions on a variable. In the below example we have used upperBound wildcard to pass integers, calculate sum of it and change it double and print it.

Unbounded Wildcards:
Unbounded wildcards is used for unknown types. It can be of any type, Integer or String or object etc..

Lower Bound Wildcards:
Lower Bound Wildcards restricts the unknown type to be specific. (Upper Bound relaxes the restrictions)

 

 

Read More

Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift

Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift:
Java Operators are basically divided into six types,

  • Arithmetic Operators
  • Relational Operators
  • Assignment Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise Operators

In this article, We are going to cover Bitwise Operators. We might face some questions in interviews regarding Bitwise operators. So lets us understand what are bitwise operators with examples.

There are 3 types of Bitwise Operators,

  • Left Shift
  • Right Shift
  • Unsigned Right Shift

Before going ahead, Let us understand what these operators do,

Left Shift Operator:

  • Left shift Operator is declared as <<
  • Left shift operator performs the operation of Multiplication
  • The sign of the the integer, Positive or negative impacts the result of left shift operator
  • Example:
    • 2 << 5
    • Output will be 64. (2^0 * 2^1*…2^5)

Right Shift Operator:

  • Right shift operator is declared as >>
  • Right shift operator performs the operation of Division
  • The sign of the integer, Positive or negative impacts the result of Right Shift Operator
  • Example:
    • 2 >> 5
    • Output: 0, (5 is divided by 2)

Unsigned Right Shift Operator:

  • Unsigned Right Shift Operator is declared as >>>
  • Irrespective of sign, It shifts the bits to 0.
  • Example: -14 >>> 2
    • This is include 2 zero’s (>>>2 — we are requesting it to shift 2 bits) to the left, followed by the value

Once we go through the example, We will be able to understand this clearly.

Output:

op1

Now let us see how this output works,

First we are getting the binary value of Both +7 and -7

7 << 2: Left shift is for multiplication,
so,

7^0 = 7
7^1=7
7^2=14
Actual value is 28 and Binary value is 11100 –> Left Shift Operator Output.

Now for the Second Output,
Right Shift Operator is for division,

7 >> 2: Right Shift for Division,

2 Divided by 7, Not divisible so the value is 1. –> Right Shift Operator Output

Now the Unsigned Right Shift Operator,

7 >> 2 and 7>>>2 are always same, except 2 Zero’s are added to the left of the output. 
-7 >>> 2:
Binary value of -7: 11111111111111111111111111111001, Now we shift 2 Zero’s to the left,
Output is,
00111111111111111111111111111110.

If we use, -7>>> 3 (3 zero’s to the left) Output will be,
00011111111111111111111111111111

Read More

Comparable and Comparator in Java

Comparable and Comparator in Java:

What is Comparable and Comparator?
Comparable is an interface used for sorting the objects. It supports Single sorting only.
Comparator is an interface used for Sorting, but supports multiple sorting.

Difference Between Comparable and Comparator:

Comparable Comparator
Compatable interface is used for Single sorting and overrides CompareTo() Comparator interface is used for Multiple Sorting and overrides Compare()
java.lang.Comparable java.util.Comparator


Comparable Example:
In comparable, We select a single object and compare with others to sort it. In this example, We are going to select one number and compare it with other numbers and sort them.

 

Output:

comparable

Comparator Example:
In comparator, We select two objects and compare them with each other and make the sort.

Output:
comparator

 

 

Read More

OOPS Concepts – Inheritance, Polymorphism, Abstraction and Encapsulation

OOPS Concepts – Inheritance, Polymorphism, Abstraction and Encapsulation:
What is OOPS?
Object Oriented Programming (OOP) is a methodology to write a program using classes and objects.

What is Inheritance?
When one object gets all the properties of super class or parent class is known as Inheritance. Subclass can also have its own properties in addition to parent class properties.

What is Polymorphism?
An object that takes various forms is known as Polymorphism.

What is Abstraction?
Hiding implementation details and showing essential features is known as abstraction.

What is Encapsulation?
Encapsulating (wrapping) the data and code into a single entity is known as Encapsulation.

Encapsulation and Abstraction seems like almost same, Let us see the difference between encapsulation and abstraction.

Abstraction Encapsulation
Abstraction helps at design level Encapsulation helps at implementation level
Abstraction hides irrelevant data and shows what is required Encapsulation hides the data to protect it from other developers

Inheritance Example:
We have a class Employee that has one property employeeName. We have another class ContractEmployee that has property salary. Now ContractEmployee extends Employee class. So ContractEmployee class can use the property  employeeName of Employee Class. This is known as Inheritance.

Output: Inheritance

inheritance
Polymorphism:
When one object takes various forms. Before proceeding to example, We must know what is Method Overriding and Method Overloading in Polymorphism.

Method Overriding:
When same method name used in both Parent class and subclass with same arguments and same return type, Then the method can be overridden.

We need to make sure,

  • Arguments and Return type should be same for the method in parent class and subclass
  • Subclass must extend parent class to implement Method Overriding
  • Access level should not be restrictive

Method Overloading:
Method overloading is two or more methods having same name both in parent class and subclasses but with different arguments.

In this example, We have a method Display() in Parent class (Employee) and Subclass (ContractEmployee). We have a Calculate method both in Parent class and Subclass but with different arguments. We have created objects and we call methods in Display() method. We have implemented both Method Overriding and Method Overloading in this example.

Output: Polymorphism

polymorphism

Abstraction:
Hiding Irrelevant data and show only necessary data.

In this example, We have an abstract class with an abstract method and non-abstract method. So when abstract class is extended, it shows abstract method but hides non-abstract method. Showing only the necessary method and hiding unwanted method is known as abstraction.

Output: Abstraction

abstraction

Encapsulation:
Hiding data from outside world.

In this example, We have two properties, String name and string department. We have assigned name = “Beta” and department = “Java”. These properties are accessible only within the same class and outside class cannot access these properties. But outside class can use getters and setters for accessing variables. Thus the Beta and Java are hided to outside class.

Output: Encapsulation

encapsulation

Read More