Saturday, 20 July 2019

Bean Scopes in Spring

1.Singleton Scope:(Default)
Scopes a single bean definition to a single onject instance per IOC container.

eg:
<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld">
<constructor-arg value="Welcome to Search Endeca" scope="singleton" />
<!--  <property name="greet" ref="helloGreeting" />-->
</bean>

2.Prototype:
Scopes a single bean definition to any number of object instances.

3.Request:
Scopes a single bean definition to the lifecycle of a single HTTP request, that is each HTTP request
has its own instance of a bean created of a single bean definition.

4.Session:
Scopes a single bean definition to the lifecycle of an HTTP Session.

5.Global Session:
Scope a single bean definition the lifecycle of a global HTTP Session.

6.Application:
Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of
a web-aware Spring ApplicationContext.

Some Important points to be remembered here.

Singleton beans with prototype-bean dependencies
When you use singleton-scoped beans with dependencies on prototype beans, be aware that
dependencies are resolved at instantiation time. 

Thus 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 singletonscoped bean.

Request, session, and global session scopes

The request, session, and global session scopes are only available if you use a web-aware
Spring ApplicationContext implementation (such as XmlWebApplicationContext).

AutoWiring Modes in spring

The Spring container can auto wire relation between collaborating beans . you can allow spring to resolve collaborators(associations) automatically for your bean by inspecting the contents of the application context.

Advantages:

Significantly reduce the need to specify the properties or constructor arguments.

1.No Autowiring:

No Auto wiring bean reference must be defined via a reference element.

2.ByName:

Auto wiring by property name spring looks for a bean with the same name as the property that needs to be autowired.

package com.searchendeca.application;

public class GreetingName {

private String name;

public String getName() {
return "Hello::"+name;
}

public void setName(String name) {
this.name = name;
}


}

package com.searchendeca.application;

public class HelloWorld {

private GreetingName greet;

public GreetingName getGreet() {
return greet;
}

public void setGreet(GreetingName greet) {
this.greet = greet;
}
static HelloWorld  clientService = new HelloWorld();

private String mMessage;

public String getMessage() {
return mMessage;
}

public void setMessage(String pMessage) {
this.mMessage = pMessage;
}


public HelloWorld hello() {
return clientService;
}
}


<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "byName"> // here the value greet been autowired.
<property name="Message" value="Welcome to Search Endeca" />
<!--  <property name="greet" ref="helloGreeting" />-->
</bean>

<bean id="greet" class="com.searchendeca.application.GreetingName">
<property name="name" value="Syed" />
</bean>


public class Hello {
@SuppressWarnings("resource")
public static void main(String[] args) {
// loading the definitions from the given XML file
//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/resources/applicationContext.xml");
//PropertiesSample service = (PropertiesSample) context.getBean("configBean");
HelloWorld service = (HelloWorld) context.getBean("helloWorldService");

// Properties message = service.getProperties();
/*System.out.println(service.getNameList());
System.out.println(service.getNameSet());
System.out.println(service.getPersonMap());

System.out.println(service.getProperties());*/
System.out.println(service.getGreet().getName());

//System.out.println(message);
//set a new name
//service.setMessage("Spring");
//message = service.getMessage();
//System.out.println(message);
}
}

Output: Hello::Syed

3.By Type:

Allows a property to be autowired if exactly one of the bean property type exists in the configuration file.

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "byType">
<property name="Message" value="Welcome to Search Endeca" />
<!--  <property name="greet" ref="helloGreeting" />-->
</bean>

<bean id="greet" class="com.searchendeca.application.GreetingName">
<property name="name" value="Syed" />
</bean>


4.By Constructor:

Analogous to byType, but applies to constructor arguments. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "constructor">
<constructor-arg value="Welcome to Search Endeca" />
<!--  <property name="greet" ref="helloGreeting" />-->
</bean>

<bean id="greet" class="com.searchendeca.application.GreetingName">
<property name="name" value="Syed" />
</bean>


package com.searchendeca.application;

public class HelloWorld {



public HelloWorld(GreetingName greet, String mMessage) {
super();
this.greet = greet;
this.mMessage = mMessage;
}
private GreetingName greet;

public GreetingName getGreet() {
return greet;
}

public void setGreet(GreetingName greet) {
this.greet = greet;
}
//HelloWorld  clientService = new HelloWorld();

private String mMessage;

public String getMessage() {
return mMessage;
}

public void setMessage(String pMessage) {
this.mMessage = pMessage;
}


/*public HelloWorld hello() {
return clientService;
}*/
}

Limitations of Autowiring.

Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions.

It also has the chances of overiding the autowiring,cannot autowire the primitives such as string and classes.

Excluding a bean from autowiring

In Spring’s XML format, set the autowire-candidate attribute of the <bean/> element to false;for excluding a bean from autowiring.

<bean id="greet" class="com.searchendeca.application.GreetingName" autowire-candidate="false">
<property name="name" value="Syed" />
</bean>

Wednesday, 17 July 2019

Dependency injection in Spring

As we know what the dependency injection means. process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. 

As I already told if the constructors apart from the default constructor how to handle it , can be seen in the below posts.

There are two types of the Dependency Injection.

1.Constructor-based dependency injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. Calling a static factory method with specific arguments to construct the bean is nearly equivalent, and this discussion treats arguments to a constructor and to a static factory method similarly

Constructor argument resolution

Constructor argument resolution matching occurs using the argument’s type. If no potential ambiguity exists in the constructor arguments of a bean definition, then the order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor when the bean is being instantiated. Consider the following class:

eg:
package x.y;
public class Foo {
    public Foo(Bar bar, Baz baz) {
        // ...
    }
}
<beans>
    <bean id="foo" class="x.y.Foo">
        <constructor-arg ref="bar"/>
        <constructor-arg ref="baz"/>
    </bean>
    <bean id="bar" class="x.y.Bar"/>
    <bean id="baz" class="x.y.Baz"/>
</beans>

In the above example there are two class Bar and Baz hence no Issue, spring resolves through the type.

package examples;
public class ExampleBean {
    // Number of years to calculate the Ultimate Answer
    private int years;
    // The Answer to Life, the Universe, and Everything
    private String ultimateAnswer;
    public ExampleBean(int years, String ultimateAnswer) {
        this.years = years;
        this.ultimateAnswer = ultimateAnswer;
    }
}

//mentioning the value spring directly resolves it.

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>

Use the index attribute to specify explicitly the index of constructor arguments of different type. For example. If am having the same type then this Index will be useful.

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>

In addition you can also mention the name for the disambiguation.

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>


2.Setter-based dependency injection

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

eg:
<bean id="exampleBean" class="examples.ExampleBean">
    <!-- setter injection using the nested ref element -->
    <property name="beanOne">
// we are passing through the setter based dependency.
        <ref bean="anotherExampleBean"/>
    </property>
    <!-- setter injection using the neater ref attribute -->
    <property name="beanTwo" ref="yetAnotherBean"/>
    <property name="integerProperty" value="1"/>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

public class ExampleBean {
    private AnotherBean beanOne;
    private YetAnotherBean beanTwo;
    private int i;

//Code Level to set the property.

    public void setBeanOne(AnotherBean beanOne) {
        this.beanOne = beanOne;
    }
    public void setBeanTwo(YetAnotherBean beanTwo) {
        this.beanTwo = beanTwo;
    }
    public void setIntegerProperty(int i) {
        this.i = i;
    }
}


Instantiating beans

Once If we create a bean, then we wanted to use in our class we need to follow some way because of which it gets initiated, after that we can use it in our application.

There are three way We can initiate the bean.

1. Instantiation with a Constructor.

In My previous posts, if you see that it is initated with the constructor. As soon we mention the bean in the defintion file and no constructor defined it will considers it as the default constructor with no arguments and initailizes it.Simply specifying the bean class should suffice. However, depending on what type of IoC you use for that specific bean, you may need a default (empty) constructor.
This will not get initialized when you define any constructor apart from the default, inorder to handle this situation, we can see in the upcoming posts.

We will get the below error when try to run.

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.searchendeca.application.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.searchendeca.application.HelloWorld.<init>()

If I define the default constructor then it started working. When means to initialize we require the default constructor.

eg:<bean id="helloWorldService"class="com.searchendeca.application.HelloWorld">
</bean>

2. Instantiation with a static factory method

When defining a bean that you create with a static factory method, you use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method itsel
eg:

<bean id="clientService" class="examples.ClientService" factory-method="createInstance"/>

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}
    public static ClientService createInstance() {
        return clientService;
    }
}

3.Instantiation using an instance factory method

This is similar to the static factory method but here you will not mention the class and define the factory-bean attribute which has the method defined.

eg:
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>
<!-- the bean to be created via the factory bean -->
<bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>


public class DefaultServiceLocator {
    private static ClientService clientService = new ClientServiceImpl();
    private DefaultServiceLocator() {}
    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

One factory class can also hold more than one factory method.

Getting started in to Spring Framework

Spring Framework Overview.

Spring Framework makes developing of enterprise java applications easier. It supports groovy,kotlin as alternate apart from java.Spring actually means "Different things in different context". It is divided in to modules and we can utilize the modules based on our needs to the application. Spring Framework also provides the foundation support for different application architectures including messaging, transaction data and persistence and web.

IOC Container (Inversion of Control)

IOC is also known as dependency Injection(DI).It is a process where by objects define their dependencies only through the Constructor arguments,arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.The container then injects those dependencies when it creates the bean.

Bean.

The Objects that form the backbone of your application and that are managed by the spring IOC container are called beans.A bean is an object that is instantiated assembled and otherwise managed by a spring IOC Container.

Application context.

Application context interface represents the spring IOC container and is responsible for instantiating configuring and assembling the beans.The Container gets its instructions on what objects to instantiate configure and assemble by reading the configuration meta data.Several implementations of the ApplicationContext interface are supplied out-of-thebox with Spring. In standalone
applications it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext

This Configuration metadata is represented in XML,Java annotations or the Java Code.

Here we can see how to create the application.

Create a New Maven Project and select the option to skip the architypes. If we are creating the Maven Project then we should be knowing of the below terms.

GroupId.

uniquely identifies your project across all projects. A group ID should follow Java's package name rules. This means it starts with a reversed domain name you control. For example,

com.searchendeca

A good way to determine the groupId is to use project structure thst is if the current project has a multiple module project, it should append a new identifier to the parents.

eg: com.searchendeca.plugin
    com.searchendeca.reporting.
Artifact Id.

It is the name of the jar without version. If you created it then you can choose whatever name you want with the lower case letters
and no strange symbols.

Eg: maven,commons-math

Version.

If you distribute then you can choose any typical version with number and dots.

Step 1.Based on the above information create the project. Add the Following the POM.xml

 <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
</properties>
Once you add the below then the maven will download the required jars and put in the lib.

Step 2.To create the Configuration file in the path. /src/main/resources named applicationContext.xml

with the following contents.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">


<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld">
<property name="Message" value="Welcome to Search Endeca" />
</bean>
</beans>

Step 3.Next Create a bean.

package com.searchendeca.application;

public class HelloWorld {

private String mMessage;

public String getMessage() {
return mMessage;
}

public void setMessage(String pMessage) {
this.mMessage = pMessage;
}
}

Step 4.Create a Main class.

package com.searchendeca.application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Hello {
@SuppressWarnings("resource")
public static void main(String[] args) {
// loading the definitions from the given XML file
//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/resources/applicationContext.xml");
HelloWorld service = (HelloWorld) context.getBean("helloWorldService");
String message = service.getMessage();
System.out.println(message);
//set a new name
service.setMessage("Spring");
message = service.getMessage();
System.out.println(message);
}
}

//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Look at the ApplicationContext created using the ClassPathXMlApplication context the other way to remember or
create the context is like below using the FileSystemXmlApplicationContext.

//ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/resources/applicationContext.xml");

After creating the application run as the java application.

It will print the following output.

Output:

Welcome to Search Endeca
Spring

Happy Learning !!!

Sunday, 14 July 2019

Thread States

Blocked

A thread that has suspended execution because it is waiting to acquire a lock.

New

A thread that has not begun execution.

Runnable

A thread that is currently executing or will execute when it gains access to the CPU.

Terminated

A thread that has completed execution.

Timed_waiting

A thread that has suspended execution for a specific period of time, such as when it has called sleep(). This state is also entered when a timeout version of wait() or join() is called.

Waiting

A thread that has suspended execution because of it is waiting for some action to occur. For eg it is waiting because of a call to a nontimeout version of wait() or join().

Exploring IO in Java

Reading the Input from the console is very easy and developers may use it without even thinking. Same like that is very important to understand what are the different ways of reading it, when to use the approach.

There are three ways we can read the input from the user using the console.

1.Using Buffered Reader Class.
2.Using Scanner Class.
3.Using Console Class.
Using Buffered Reader Class
Using Scanner Class
Using Console Class
This is used to read the result include in the order line.
This is used to parse primitive typesand strings using regular expressions.
Preferred way of reading the innour from the Console.
Advantage: The Input is Buffered for efficinnt reading
Advantage: Convinient for Primitive types and using the regular expressions.
Advantage: Reading password without echoing the entered chars.
Reading methods are Synchronized
Drawbacks: The Wrapping code is hard to remember.
Drawbacks: The Reading methods are not synchronized.
Drawbacks: Does not work in non-interactive environement.
Usage:
String buffer=null;
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the Buffer terms:");
buffer=buf.readLine();
System.out.println(buffer);
} catch (IOException e) {
e.printStackTrace();
}
Usage:
String scanner=null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Scanner terms:");
scanner=sc.nextLine();
System.out.println(scanner);
Usage:
String console=null;
Console con = System.console();
System.out.println("Enter the Console terms");
console=con.readLine();
con.printf("%s\n", console);
Output:
Enter the Buffer terms:
Syed Ghouse Habib
Syed Ghouse Habib
Output:
Enter the Scanner terms:
Syed Ghouse Habib
Syed Ghouse Habib
Output:(Note: I am using IDE)
Exception in thread "main" Enter the Console terms
java.lang.NullPointerException
at com.searchendeca.thread.sample.ReadingInput.main(ReadingInput.java:30)


Difference Between println and printf.

println() prints a new blank line and then your message. printf() provides string formatting similar to the printf function in C. printf() is primarily needed when you need to print big strings to avoid string concatenaion in println() which can be confusing at times. (Although both can be used in almost all cases).

Eg. int a = 10;int b = 20;

println("a: " + a + " b: " + b); //Tedious String Concatenation

printf("a: %d b: %d\n", a, b); // Output using string formatting.

While printf() enables you to print fractional outputs up to any decimal place in a single line, the same task using println() can get very complex.

Eg. printf("%.6f",x); // prints x up to 6 decimal places.

Serialization in Java

It is the process of writing the state of the object to a byte stream. This is useful when you want to save the state of your program to persistent storage area such as a file.At later time you mayrestore these objects by using the process of deserialization.

Objects only that implement the "Serialization interface" can be saved and restored. If we define the object as Transient then we cannot serialize the object.

Recommended learning.

I recommend you to go through the difference between the Transient and  volatile.

Externalizable.

By Default the Serialization happens automatically, when the user wants to have control over this process then there comes this externalizable in picture.

All through the process inStream is the byte stream from which the object is to be read, and
outStream is the byte stream to which the object is to be written

If we want to achieve the serialization below are important.

Object Output.
This is called to serialize the object.

Object Output stream.
This is the class responsible for the writing the objects in to the stream.

Object Input.
This is called to deserialize the Object.

Object Input Stream. 
It is responsible for reading the Objects from a stream.

By Using all of this concepts I have written a small program where we can understand this serialization.

In this  I have created the SerializationExample as Vo class by implementing the Serializable interface .

In the MyClass I am writing this List<SerializationExample> Object to the file and reading from the file.

We can discuss about the complex implementations in the upcoming posts.

package com.searchendeca.sample;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SerializationExample implements Serializable {
transient String s;
int i;
public SerializationExample(String s1,int i1) {
this.s=s1;
this.i=i1;
}
public String toString() {
return "s=" + s + "; i=" + i;
}

}

class MyClass{

public static void main(String args[]) {
//Serialize the object

try {
List<SerializationExample> listObj = new ArrayList<>();
ObjectOutputStream outObj = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Syed\\Sample\\src\\com\\searchendeca\\thread\\sample\\serial.txt"));
SerializationExample se = new SerializationExample("Syed Ghouse", 1);
SerializationExample se1 = new SerializationExample("Syed", 2);
listObj.add(se);
listObj.add(se1);
outObj.writeObject(listObj);
}catch(IOException ie) {
ie.printStackTrace();
}

//Deserialize the object

ObjectInputStream inObj = null;
List<SerializationExample> dse = null;
try {
inObj = new ObjectInputStream(new FileInputStream("C:\\Users\\Syed\\Sample\\src\\com\\searchendeca\\thread\\sample\\serial.txt"));
dse = (List<SerializationExample>) inObj.readObject();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dse.stream().forEachOrdered(System.out::println);
}
}

Output:

s=null; i=1
s=null; i=2

Saturday, 13 July 2019

Thread Concepts

To Find the Thread is alive or not, we can use the below method.

final boolean isAlive() 
To determine whether a thread has finished, first you call isAlive() on thread, that will more commonly use to wait for a thread to finish is called join().

final void join() throws Interrupted Exception.
This will make the thread to finish its process.

notify()
wakes up thread that called wait() on the same object.

notify all()
wakes up all the thread that called wait on the same object.

What is a Race Condition in Thread.

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Below is the example for the Race Conditions in the thread

package com.searchendeca.thread.sample;

class MultiThreadNonSyncDemo {


//For Sync Use the Synchronized Keyword Here
 void call(String pName){
System.out.print("[" + pName);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Interrupted");
e.printStackTrace();
}
System.out.println("]");
}

}
class Caller implements Runnable {
String msg;
MultiThreadNonSyncDemo target;
Thread t;
public Caller(MultiThreadNonSyncDemo targ, String s) {
target = targ;
msg = s;
if(s.equals("Hello3")) {
t = new Thread(this);
t.start();
t.setPriority(1);
}
else {
t = new Thread(this);
t.start();
}
}
public void run() {
target.call(msg);

}
}
class MainMultiSyncJoin {

public static void main(String args[]) {
MultiThreadNonSyncDemo target = new MultiThreadNonSyncDemo();
Caller m1= new Caller(target, "Hello1");
Caller m2= new Caller(target, "Hello2");
Caller m3= new Caller(target, "Hello3");
try {

m1.t.join();
m2.t.join();
m3.t.join();
System.out.println("**One is Alive::"+m1.t.isAlive());
System.out.println("**Two is Alive:"+m2.t.isAlive());
System.out.println("**Three is Alive:"+m3.t.isAlive());
}catch(InterruptedException IE) {
IE.printStackTrace();
}
}
}

Output:

[Hello1[Hello2[Hello3]
]
]
**One is Alive::false
**Two is Alive:false
**Three is Alive:false


Here all the three threads start and execute and wanting to prove among them self.

synchronized: This comes to play as a solution for the race conditions.

To avoid the race condition we can use the below two methods .

1. using the synchronized methods.
2. using synchronized statements.

1. using the synchronized methods.
//For Sync Use the Synchronized Keyword Here
synchronized void call(String pName){
System.out.print("[" + pName);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Interrupted");
e.printStackTrace();
}
System.out.println("]");
}

Update the following snippet int the above program.

Output:

[Hello1]
[Hello3]
[Hello2]
**One is Alive::false
**Two is Alive:false
**Three is Alive:false

2. using synchronized statements.
In the above demo program defined alter the run method like this.Update the following snippet int the above program.

public void run() {
synchronized (target) {
target.call(msg);
}

Output:

[Hello1]
[Hello3]
[Hello2]
**One is Alive::false
**Two is Alive:false
**Three is Alive:false

Thread Priorities

A thread priority is used to decide when to switch from one running thread to the next. This is called as Context switch.

There are certain rules, where the thread can context switch.

1. A thread can voluntarily relinquish control.
2.A thread can be preempted(Serve) by higher priority thread.

We can set the thread a priority which means that it will not execute in higher speed, when compared to the low priority thread it means threads will be utilizing the CPU based on the higher priority.

Also thread priories will be used by the Thread Scheduler to decide when each thread should be allowed to run.  In Theory, over a given period of time higher priority thread gets more CPU time than the lower priority threads.

Priority can range from 1 to 10.
min_priority to max_priority. To return a thread to default priority, specify it as normal_prioerity which is currently 5.

Thread Creation in Java

Thread Can be defined as the smallest execution part in with the process(an instance of the program running in computer).

We can see how to create a thread and rules around it in the coming blogs.
Thread Can be created using the below two approaches.

1. Implementing the runnable Interface.
2. Extending the Thread class.

Most of us if we tell there are two ways the next question to be asked his what is the best approach.
Many developers including me thinks that class should be extended when they are being enhanced or modified in someway.
So if will not be overide any of the threads other methods, it is probably best simply to implement the runnable.

1. Implementing the runnable Interface.

package com.searchendeca.thread.sample;

 class ThreadDemoImplements implements Runnable {

Thread t;
ThreadDemoImplements(){
t= new Thread(this,"MY Threadd");
t.start();
}

@Override
public void run() {
for(int n = 5; n > 0; n--) {
System.out.println("*********"+n);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}

}

}
 class calling {

public static void main(String args[]) {
new ThreadDemoImplements();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}

 }

 2. Extending the thread class.

 package com.searchendeca.thread.sample;

 class ThreadDemoExtends extends Thread {

ThreadDemoExtends(){
super("Demo Thread");
start();
}


public void run() {
for(int n = 5; n > 0; n--) {
System.out.println("*********"+n);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}

}

}
 class callingExtends {

public static void main(String args[]) {
new ThreadDemoExtends();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}

 }

The difference between the thread creation using Implementing the runnable and  extending the thread class is no need to create the Instance in extending the thread class.

Producer Consumer Problem

Hi Readers Before getting in to the Producer Consumer Problem also know as bounder-buffer problem. which means producer is producing it and consumer is waiting for it,this continues to be wasting CPU Cycles.

Producer Consumer Problem is the classic example for this and we see through the below example 

Consider Below four classes:

// GetSet, the queue that you’re trying to synchronize; 
class GetSet {
int n;
boolean valueSet = false;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}

//Producer, the threaded object that is producing queue entries; 
class Producer implements Runnable {
GetSet q;
Producer(GetSet q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}

//Consumer, the threaded object that is consuming queue entries; 
class Consumer implements Runnable {
GetSet q;
Consumer(GetSet q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}

//PC, the tiny class that creates the single GetSet,Producer, and Consumer.
class PC {
public static void main(String args[]) {
GetSet q = new GetSet();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Press Control-C to stop.
Put: 0
Put: 1
Put: 2
Put: 3
Put: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4


As you can see, after the producer put 1, the consumer started and got the same 1 five
times in a row. Then, the producer resumed and produced 2 through 7 without letting
the consumer have a chance to consume them.

The Solution to avoid this pooling Java includes an elegant inter process communication mechanism via
the wait( ), notify( ), and notifyAll( ) methods.

Please see the following snippet

class GetSet {
int n;
Boolean visited=Boolean.FALSE;
synchronized int get() {
if(!visited) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Got: " + n);
notify();
visited=Boolean.FALSE;
return n;
}
synchronized void put(int n) {
if(visited) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.n = n;
visited=Boolean.TRUE;
notify();
System.out.println("Put: " + n);
}
}



Here We are Producing and consuming in the above way, When using the above way Producer will be Suspended until the Producer notifies it is able to produce, and consumer can consume it.some output from this program, Hence wasting the CPU Cycles .
which shows the clean synchronous behavior:

Press Control-C to stop.
Put: 0
Got: 0
Put: 1
Got: 1

Hope Producer Consumer Problem is solved . Happy Reading !!!

Sunday, 30 December 2018

Indexing Process in Solr

The Following post defines how exactly the Indexing process in Solr works.

When we take the Indexing part there are multiple ways we can achieve in Solr such as.

  • Indexing using the post.jar
  • Indexing using the dataImport handlers.
  • Indexing by executing the curl commands.

We will concentrate more on the first two pointers of Indexing.

Indexing using the post.jar

As I already mentioned in previous posts that the Solr Ships with the exampleDocs from where we can do getting started.

Navigate to C:\Dev\solr-7.5.0\example\exampledocs

In this folder we have the sample xml and json files,using which we can use to Index the data.Also In the Same folder We have the post.jar that process these documents and Index it .

C:\Dev\solr-7.5.0\bin>java -jar -Dc=example -Dauto C:\Dev\solr-7.5.0\example\exampledocs\post.jar C:\MicroservicesPOC\solr-7.5.0\solr-7.5.0\example\exampledocs\ .*

Where -Dc is the name of the core.

-Dauto is the location where the post.jar resides.

This post.jar reads the collection and Index the documents given to it. But the condition here is that we have to follow the format the post.jar expects, otherwise the Indexing will not happen.

Indexing using the dataImport handlers

For the Second way of Indexing checkout my detailed post here using the DataImport handler.

Happy Indexing!!!

Tuesday, 25 December 2018

My First Lamda Expression using java 8

I was late trying out my first lambda expressions !!!!! But still I will give a try to sort the names using the Last Name. Here is my Code.


Step:1 Create a Pojo Class 

FileName:Person.java

package com.mycommercesearch.solr;

public class Person {
private String firstName;

private String lastName;

private int age;

@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
}

public Person(String firstName, String lastName, int age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}



Step:2 Create Interface NameSorter 

FileName:NameSorter.java

package com.mycommercesearch.solr;

import java.util.List;

@FunctionalInterface
public interface NameSorter {
void soryByLastName(List<Person> person,String arrangement);
}


Step:3 Create a main class

FileName:NameTest.java

package com.mycommercesearch.solr;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class NameTest{
public void invokeSample(NameSorter nameTest,List<Person> person,String arrangement) {
nameTest.soryByLastName(person,arrangement);
}

public static void main(String args[]) {
//Here I have Initialized Person array with custom values.
List<Person> myPerson = Arrays.asList(new Person("Syed", "Ghouse", 27),
new Person("Manoj", "Kumar", 45),new Person("Chetan", "Bagath", 50),new Person("Eddapadi", "Palaniswamy", 60),new Person("Paneer", "Selvam", 55));
//Here I have written the lamda expression to print the List
SamplerTest sortName = (person,arrangeMent) -> {
if(!person.isEmpty()) {
person.forEach(ps-> System.out.println("Sorting using the last Name "+arrangeMent+"::"+ps.getFirstName()+" "+ps.getLastName()));
}
};
//Creating the object for my class
NameTest nameTest= new NameTest();
//Passing the behaviour to my interface
nameTest.invokeSample(sortName,myPerson,"Before");
//Invoking the sort by LastName
nameTest.sortLastName(myPerson);
//Passing the sorted bahviuor back to my previous lamda
nameTest.invokeSample(sortName,myPerson,"after");
}


public void sortLastName(List<Person> pes) {
Collections.sort(pes,(Person o1,Person o2)->{
Person p1= (Person)o1;
Person p2=(Person) o2;
return p1.getLastName().compareTo(p2.getLastName());
});
}
}


Output will be in the following format:


Sorting using the last Name Before::Syed Ghouse
Sorting using the last Name Before::Manoj Kumar
Sorting using the last Name Before::Chetan Bagath
Sorting using the last Name Before::Eddapadi Palaniswamy
Sorting using the last Name Before::Paneer Selvam

Sorting using the last Name after::Chetan Bagath
Sorting using the last Name after::Syed Ghouse
Sorting using the last Name after::Manoj Kumar
Sorting using the last Name after::Eddapadi Palaniswamy
Sorting using the last Name after::Paneer Selvam


We can look more on how to use the lamda expressions on our daily coding ways in the upcoming posts.

Happy Expressions!!!!