<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/">

<channel>
	<title>java Archives - Manish Sanger</title>
	<atom:link href="https://www.manishsanger.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.manishsanger.com/tag/java/</link>
	<description>Java, J2EE, Spring Framework, application security,big data,database,design patterns,hibernate,j2ee,java,jdbc,micro-services,mongodb,multithreading,nosql</description>
	<lastBuildDate>Fri, 06 Apr 2018 13:23:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Introduction to Spring Boot</title>
		<link>https://www.manishsanger.com/introduction-to-spring-boot/</link>
					<comments>https://www.manishsanger.com/introduction-to-spring-boot/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Fri, 06 Apr 2018 13:22:13 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[microservices]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=372</guid>

					<description><![CDATA[<p>What is Spring Boot? Spring is a popular Java-based framework for building web and enterprise grade application. spring framework provides various modern features via its various projects. Spring team created Spring Boot project to create standalone, production-ready spring based executable applications. Most of the spring boot application requires minimal spring configuration. Why Spring Boot? In [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/introduction-to-spring-boot/">Introduction to Spring Boot</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>What is Spring Boot?</strong><br />
Spring is a popular Java-based framework for building web and enterprise grade application. spring framework provides various modern features via its various projects.<br />
Spring team created Spring Boot project to create standalone, production-ready spring based executable applications. Most of the spring boot application requires minimal spring configuration.</p>
<p><strong>Why Spring Boot?</strong><br />
In a traditional monolithic approach for developing web/RESTful application, a WAR is created and deployed on a web server like: Tomcat, Jboss, IBM WebSphere etc.<br />
From a microservices point of view, we need to develop services as executable, self-contained JAR files with an embedded HTTP listener.</p>
<p><strong>Spring Boot features:</strong></p>
<ol>
<li style="list-style-type: none;">
<ol>
<li><strong>Self-Contained web server:</strong> We can easily embed HTTP listeners for the web application. We can easily create a self-contained HTTP server using embedded tomcat, jetty etc.</li>
<li><strong>Standalone application:</strong> We can create a standalone executable application. It has SpringApplication class which provides the convenient way to bootstrap a spring application which can be started from the main method just by calling static method SpringApplication.run().</li>
<li><strong>Externalized configuration:</strong> It allows us to externalize the configuration so that we can work with the same application in various environments. We can use YAML files to externalize the configuration.</li>
<li><strong>YAML Support:</strong> It provides support for YAML configuration by default.</li>
<li><strong>Application Properties:</strong> It provides a rich set of application properties, for example: server-port, application-name and many more.</li>
<li><strong>Actuator:</strong> It provides production readiness by actuators such as metrics and health check.</li>
<li><strong>Type-safe configuration:</strong> It also provides a strong type-safe way to handle the configuration by allowing the developer to create a bean and populating it with the property value from a configuration file using annotation.</li>
<li><strong>Logging:</strong> It provides out of the box logging for all internal logging. Logback is provided by default without any additional configuration, which can be altered if needed.</li>
<li><strong>Security:</strong> It provides the feature of enabling the basic security by using the spring boot started security. It enables the basic security by default, which can be further enhanced to utilize the full strength of Spring security.</li>
</ol>
</li>
</ol>
<p><strong>Related Articles:</strong><br />
<a href="https://www.manishsanger.com/getting-started-with-spring-boot/"><strong>Getting started with Spring Boot, Create your first REST API application</strong></a></p>
<p>The post <a href="https://www.manishsanger.com/introduction-to-spring-boot/">Introduction to Spring Boot</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/introduction-to-spring-boot/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Getting started with Spring Boot, Create your first REST API application</title>
		<link>https://www.manishsanger.com/getting-started-with-spring-boot/</link>
					<comments>https://www.manishsanger.com/getting-started-with-spring-boot/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Fri, 06 Apr 2018 12:50:47 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[microservices]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=364</guid>

					<description><![CDATA[<p>Spring Boot is been created for Rapid development. In this article will go through the steps to create first basic REST API using Spring Boot. We will see the more advanced version of this application in upcoming articles on microservices. Prerequisite: 1. Maven 3.X 2. Java 1.8/1.7 Getting Started &#8211; Step by Step guide The [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/getting-started-with-spring-boot/">Getting started with Spring Boot, Create your first REST API application</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Spring Boot is been created for Rapid development. In this article will go through the steps to create first basic REST API using Spring Boot. We will see the more advanced version of this application in upcoming articles on microservices.</p>
<p><span style="text-decoration: underline;"><strong>Prerequisite:</strong></span></p>
<p>1. Maven 3.X<br />
2. Java 1.8/1.7</p>
<p><span style="text-decoration: underline;"><strong>Getting Started &#8211; Step by Step guide</strong></span></p>
<p>The best way to bootstrap your Spring Boot projects is to use <a href="https://start.spring.io/" target="_blank" rel="noopener">Spring Initializr</a></p>
<p>It allows you to bootstrap various type of Spring Boot application from a simple web UI. You can select various available libraries from UI as per your requirement.</p>
<p>There are various option to generate, you can choose from Maven/Gradle project, with Java/Kotlin/Groovy and appropriate spring boot version. We will be using Maven, Java and Spring Boot 2.0.0 here.</p>
<p>Define group, artifact, name &amp; description of the application on the UI.</p>
<p>Click on &#8220;Switch to the full version&#8221; at the bottom left to see the list all available library options to be included in the project. For this article, I have selected the following as this is just a basic article to get started with Spring Boot.</p>
<p><strong>Web:</strong><br />
-Web<br />
-Jersey(JAX-RS)</p>
<p><strong>Ops:</strong><br />
-Actuator</p>
<p>Click on &#8220;Generate Project&#8221; button at the bottom of the screen to download bootstrap project with Spring Boot.</p>
<div id="attachment_365" style="width: 808px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-365" class="size-full wp-image-365" src="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png" alt="Spring Initializr- Spring Boot, bootstrap your first REST API application" width="798" height="581" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png 798w, https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr-300x218.png 300w, https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr-768x559.png 768w" sizes="(max-width: 798px) 100vw, 798px" /></a><p id="caption-attachment-365" class="wp-caption-text">Spring Initializr- Spring Boot, bootstrap your first REST API application</p></div>
<p>Import the project in your favorite IDE &#8211; Eclipse, IntelliJ Idea, STS or any other. I am using IntelliJ Idea on Mac OSX.</p>
<p>Project Structure will look like as follows:</p>
<div id="attachment_366" style="width: 310px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure.png"><img decoding="async" aria-describedby="caption-attachment-366" class="size-full wp-image-366" src="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure.png" alt="Spring boot - REST API project structure" width="300" height="359" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure.png 300w, https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure-251x300.png 251w" sizes="(max-width: 300px) 100vw, 300px" /></a><p id="caption-attachment-366" class="wp-caption-text">Spring boot &#8211; REST API project structure</p></div>
<p>Here is pom.xml dependencies, downloaded from Spring Initializr.</p>
<div id="attachment_367" style="width: 461px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies.png"><img decoding="async" aria-describedby="caption-attachment-367" class="size-full wp-image-367" src="https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies.png" alt="Spring Boot REST API - maven dependencies" width="451" height="322" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies.png 451w, https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies-300x214.png 300w" sizes="(max-width: 451px) 100vw, 451px" /></a><p id="caption-attachment-367" class="wp-caption-text">Spring Boot REST API &#8211; maven dependencies</p></div>
<p>spring-boot-starter-web &#8211; Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.</p>
<p>spring-boot-starter-actuator &#8211; Actuator provides production readiness of the application by monitoring our application, gathering metrics, understanding traffic, state of database etc. Will see actuator in more details in my next article.</p>
<p>Here is the Application file, which has the main method to run the Spring Boot application to make it executable:</p>
<pre><code class="java">@SpringBootApplication<br />
public class SpringbootdemoApplication {<br />
public static void main(String[] args) {<br />
SpringApplication.run(SpringbootdemoApplication.class, args);<br />
}<br />
}<br />
</code></pre>
<p>Create a Rest Controller, to create your first REST endpoint. Here is the code:</p>
<pre><code class="java">@RestController<br />
@RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)<br />
public class HelloController {</p>
<p>@RequestMapping("/")<br />
public ResponseEntity&lt;Response&lt;List&gt;&gt; index() {<br />
HttpHeaders headers = new HttpHeaders();<br />
List listData = new ArrayList&lt;&gt;();<br />
listData.add("This is a First REST API with Spring boot");<br />
listData.add("Test2");</p>
<p>return new ResponseEntity&lt;&gt;(new Response&lt;&gt;(HttpStatus.OK.value(),<br />
"First Spring Boot REST API is working", listData), HttpStatus.OK);<br />
}<br />
}<br />
</code></pre>
<p>I create a class named Response to convert data to JSON and define a proper response format. This is not required, but I always prefer to have a class like this as it easy to format/standardize your response and pass HTTP status code &amp;message to variety of API consumers.</p>
<pre><code class="java">@JsonInclude(value = Include.NON_EMPTY)<br />
public class Response {</p>
<p>private int status;<br />
private String message;<br />
private T data;</p>
<p>public Response(int status, String message, T data) {<br />
super();<br />
this.status = status;<br />
this.message = message;<br />
this.data = data;<br />
}</p>
<p>public Response() {<br />
super();<br />
}</p>
<p>public int getStatus() {<br />
return status;<br />
}</p>
<p>public String getMessage() {<br />
return message;<br />
}</p>
<p>public T getData() {<br />
return data;<br />
}<br />
}<br />
</code></pre>
<p>You can also use lombok project (<a href="https://projectlombok.org/" target="_blank" rel="noopener">https://projectlombok.org/</a>), if you don&#8217;t want to write/generate getters &amp; setters.</p>
<p>That&#8217;s it, now we are ready to launch our first sample Spring Boot REST API project.</p>
<p>Go to Terminal and use the following commands to run the application.<br />
<pre><code class="bash">mvn clean install<br />
java -jar springbootdemo-0.0.1-SNAPSHOT.jar<br />
</code></pre>
<p>You can also run from your IDE. I am using IntelliJ Idea, so I can run it from IDE itself.</p>
<p>Once the run is complete, you can access it on http://localhost:8080/ or via postman. We haven’t made any configuration changes to it will run on localhost and default port 8080.</p>
<p>Here is the response:</p>
<div id="attachment_368" style="width: 451px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-368" class="size-full wp-image-368" src="https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response.png" alt="Spring Boot - REST API Response" width="441" height="141" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response.png 441w, https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response-300x96.png 300w" sizes="auto, (max-width: 441px) 100vw, 441px" /></a><p id="caption-attachment-368" class="wp-caption-text">Spring Boot &#8211; REST API Response</p></div>
<p>You can access Actuator Health and Info as follows:<br />
http://localhost:8080/actuator/health<br />
http://localhost:8080/actuator/info</p>
<p>The post <a href="https://www.manishsanger.com/getting-started-with-spring-boot/">Getting started with Spring Boot, Create your first REST API application</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/getting-started-with-spring-boot/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png" length="76611" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png" width="798" height="581" medium="image" type="image/png"/>	</item>
		<item>
		<title>Microservices &#8211; An Introduction</title>
		<link>https://www.manishsanger.com/microservices-an-introduction/</link>
					<comments>https://www.manishsanger.com/microservices-an-introduction/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Mon, 02 Apr 2018 13:48:30 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[microservices]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=358</guid>

					<description><![CDATA[<p>In recent years, micro-service is getting popularity and is a buzz word in IT/Software industry. Micro-services are an architectural style or an approach to build IT systems as a set of business capabilities that are autonomous, self-contained, and loosely coupled. Its used to achieve agility, the speed of delivery and scaling. Many organizations such as [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/microservices-an-introduction/">Microservices &#8211; An Introduction</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In recent years, micro-service is getting popularity and is a buzz word in IT/Software industry.<br />
Micro-services are an architectural style or an approach to build IT systems as a set of business capabilities that are autonomous, self-contained, and loosely coupled. Its used to achieve agility, the speed of delivery and scaling.</p>
<p>Many organizations such as Netflix and Amazon used this technique to functionally partition their applications into smaller atomic units.</p>
<p>Micro-services originated from the idea of hexagonal architecture. Hexagonal architecture is also known as the Ports and Adapters Pattern.<br />
<a href="http://alistair.cockburn.us/Hexagonal+architecture">Hexagonal Architecture &gt;&gt; </a></p>
<div id="attachment_359" style="width: 962px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/Monotlithic-application.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-359" class="size-full wp-image-359" src="https://www.manishsanger.com/wp-content/uploads/2018/04/Monotlithic-application.png" alt="Monolithic Application" width="952" height="794" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/Monotlithic-application.png 952w, https://www.manishsanger.com/wp-content/uploads/2018/04/Monotlithic-application-300x250.png 300w, https://www.manishsanger.com/wp-content/uploads/2018/04/Monotlithic-application-768x641.png 768w" sizes="auto, (max-width: 952px) 100vw, 952px" /></a><p id="caption-attachment-359" class="wp-caption-text">Monolithic Application</p></div>
<p>Let&#8217;s take an example of an E-commerce application. In a typical monolithic architecture, all modules are part of the same project/package and are connected with single database technology as shown in the architecture above. Here are some of the problem, which developer and business were facing with Monolithic architecture over the period of time:</p>
<ol>
<li>In older and large applications, codebase increased over the period of time and it takes ages to build and deploy.</li>
<li>There is a technology constraint with the application, new features have to be developed with old technology stack, or it requires a huge amount of effort to upgrade the version or using latest tools and technologies available.</li>
<li>Each module is tightly coupled with other modules, so if you change one module it will impact the other module also, so maintaining the monolithic applications are more error-prone.</li>
<li>When you make a change in any module, whole application has to be built and deployed again.</li>
<li>You can&#8217;t scale only one section of the application. For example, in an E-commerce application, search and browse catalog usually have the highest load, in the monolithic approach we can&#8217;t only scale these two services only, we have to scale the whole application on separate server instances behind a load balancer.</li>
</ol>
<p>In traditional monolithic application, we build a .war or .ear and deploy it on an application server like Tomcat, JBoss, WebLogic, WebSphere etc. In micro-service architecture, each micro-service will be built as a jar, embedded with all the dependencies and run as a standalone Java process.<br />
Micro-services may also have their own containers for execution. Container technology like Docker is an ideal choice for micro-services deployment.</p>
<div id="attachment_360" style="width: 1042px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-360" class="size-full wp-image-360" src="https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture.png" alt="Microservices Architecture" width="1032" height="860" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture.png 1032w, https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture-300x250.png 300w, https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture-768x640.png 768w, https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture-1024x853.png 1024w" sizes="auto, (max-width: 1032px) 100vw, 1032px" /></a><p id="caption-attachment-360" class="wp-caption-text">Microservices Architecture</p></div>
<p><strong>Benefits of using micro-services:</strong></p>
<ol>
<li>Can use different architecture, technology and version of the technology for each micro-service.</li>
<li>Enabling experimentation and innovation. for example, recommendation engine, where we keep changing the recommendation algorithm.</li>
<li>Elastically and selectively scalable, we can select only the selected service where application receives the highest load. For example: Search and Catalog section of the e-commerce application.</li>
<li>This enables building up an organic system, where we keep adding the feature in an agile way over the period of time without impacting the existing system.</li>
<li>This helps in reduction of technology debt, we can change/upgrade technologies with much lesser effort/impact as compare to monolithic.</li>
<li>It supporting event-driven architecture, for example: In e-commerce when an order is received various service has to be invoked like: save order, update inventory, send email/SMS/push notification, data analysis, delivery etc.</li>
<li>Micro-service are the key enabler for DevOps. It advocates automating as much as possible, for example, continuous integration &#8211; testing, automatic infrastructure provisioning, automatic build, automatic deployment etc.</li>
</ol>
<p>The post <a href="https://www.manishsanger.com/microservices-an-introduction/">Microservices &#8211; An Introduction</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/microservices-an-introduction/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture.png" length="80553" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/04/Microservices-Architecture.png" width="1032" height="860" medium="image" type="image/png"/>	</item>
		<item>
		<title>Java Exception Hierarchy</title>
		<link>https://www.manishsanger.com/java-exception-hierarchy/</link>
					<comments>https://www.manishsanger.com/java-exception-hierarchy/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Wed, 28 Mar 2018 11:45:40 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[java]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=353</guid>

					<description><![CDATA[<p>As shown in the exception hierarchy, a Throwable class is a superclass of all errors and exceptions in Java. Objects those are instances of Throwable or one of its subclasses are thrown by JVM or by Java throw statement. Error: An Error is a subclass of Throwable that represents serious errors that can&#8217;t be handled. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/java-exception-hierarchy/">Java Exception Hierarchy</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div id="attachment_354" style="width: 657px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-354" class="size-full wp-image-354" src="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png" alt="Java Exception Hierarchy" width="647" height="593" srcset="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png 647w, https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy-300x275.png 300w" sizes="auto, (max-width: 647px) 100vw, 647px" /></a><p id="caption-attachment-354" class="wp-caption-text">Java Exception Hierarchy</p></div>
<p>As shown in the exception hierarchy, a <em>Throwable</em> class is a superclass of all errors and exceptions in Java. Objects those are instances of <em>Throwable</em> or one of its subclasses are thrown by JVM or by Java throw statement.</p>
<p><span style="text-decoration: underline;"><strong>Error:</strong></span><br />
An Error is a subclass of <em>Throwable</em> that represents serious errors that can&#8217;t be handled. A method is not required to declare throws clause for Error or any of its subclasses for the errors thrown during execution of the method but not caught.</p>
<p>Error and its subclasses are unchecked exceptions.<br />
Here are the examples of errors: OutOfMemoryError, StackOverflowError, AssertionError, IOError, NoClassDefFoundError etc.</p>
<p><span style="text-decoration: underline;"><strong>Exception:</strong></span><br />
Exception is a subclass of <em>Throwable</em>. Exception and its subclasses represent the problems from which a program can recover and should be handled by the application.<br />
Exception has two sub type:</p>
<p>1. <span style="text-decoration: underline;"><strong>RunTimeException or Unchecked Exception:</strong></span><br />
The classes that extends <em>RunTimeException</em> are called unchecked Exception. An unchecked exception occurs at run-time, it can&#8217;t be checked at compile time, an application should handle these exceptions. For example: NullPointerException, ArithmeticException, IllegalArgumentException, IndexOutOfBoundException etc.</p>
<p><span style="text-decoration: underline;"><strong>2. Checked Exception:</strong></span><br />
The classes that extends Throwable class except RunTimeExpception and Error are called Checked Exception. Checked exception are checked at compile time and application should handle these exceptions. For example: IOException, SQLException, FileNotFoundException, ClassNotFoundException, NoSuchMethodException etc.</p>
<p><span style="text-decoration: underline;"><strong>User-defined custom exception:</strong></span><br />
We can also create our own exception. Here are few rules:<br />
1. All exception must be a child of Throwable.<br />
2. To create a RuntimeException, we need to extend the RunTimeException class.<br />
3. To create the checked exception, we need to extend the Exception class.</p>
<p><span style="text-decoration: underline;"><strong>Reference:</strong></span><br />
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html" target="_blank">https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html</a><br />
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html" target="_blank">https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html</a></p>
<p>The post <a href="https://www.manishsanger.com/java-exception-hierarchy/">Java Exception Hierarchy</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/java-exception-hierarchy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png" length="35275" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png" width="647" height="593" medium="image" type="image/png"/>	</item>
		<item>
		<title>Type Erasure &#8211; Java Generics</title>
		<link>https://www.manishsanger.com/type-erasure-java-generics/</link>
					<comments>https://www.manishsanger.com/type-erasure-java-generics/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 20 Mar 2018 11:59:31 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[generics]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=344</guid>

					<description><![CDATA[<p>What is type Erasure? Generics in Java provide type checking at compile time and it has nothing to do at runtime. Java compiler uses Type Erasure feature to remove all generics type checking code (replace it with bound or Object if the type parameters are unbounded) in bytecode, insert type casting if necessary and generate [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/type-erasure-java-generics/">Type Erasure &#8211; Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><b>What is type Erasure?</b></p>
<p>Generics in Java provide type checking at compile time and it has nothing to do at runtime. Java compiler uses <b>Type Erasure</b> feature to remove all generics type checking code (replace it with bound or Object if the type parameters are unbounded) in bytecode, insert type casting if necessary and generate bridge methods to preserve polymorphism in extended generic types.</p>
<p>Here is an example of generic a class:</p>
<pre><code class="java">class TypeErasureExample {<br />
private T t;</p>
<p>public TypeErasureExample(T t) {<br />
this.t = t;<br />
}</p>
<p>public T getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>After compilation the type will be replaced with String as follows:</b></p>
<pre><code class="java">class TypeErasureExample {<br />
private String t;</p>
<p>public TypeErasureExample(String t) {<br />
this.t = t;<br />
}</p>
<p>public String getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><u><b>Type erasure at class or class variable level:</b></u><br />
At the class level, type parameters on the class are removed at compile time and replaced with its first bound or Object if the type parameter is unbound.<br />
Here are few examples:<br />
<b>Type erasure when type parameter is unbound:</b><br />
<pre><code class="java">class TypeErasureUnboundExample {<br />
private T t;</p>
<p>public TypeErasureUnboundExample(T t) {<br />
this.t = t;<br />
}</p>
<p>public T getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>After compilation the type will be replace with Object (because type parameter is unbound) as follows:</b><br />
<pre><code class="java">class TypeErasureUnboundExample {<br />
private Object t;</p>
<p>public TypeErasureUnboundExample(Obhect t) {<br />
this.t = t;<br />
}</p>
<p>public Object getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>Type erasure when type parameter is bound:</b><br />
<pre><code class="java">class TypeErasureExample {<br />
private T t;</p>
<p>public TypeErasureExample(T t) {<br />
this.t = t;<br />
}</p>
<p>public T getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>After compilation the type will be replaced with String (with first bound) as follows:</b></p>
<pre><code class="java">class TypeErasureExample {<br />
private String t;</p>
<p>public TypeErasureExample(String t) {<br />
this.t = t;<br />
}</p>
<p>public String getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<u><b>Type Erasure at method level:</b></u><br />
Method type parameters are converted to its parent type Object if its unbound or its bound class when its bound:</p>
<p>For example:<br />
If type parameter is unbounded:<br />
<pre><code class="java">public static <T> void genericMethod(T t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>Will be converted to following at compile time:<br />
<pre><code class="java">public static void genericMethod(Object t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>If type parameter is bounded:</p>
<pre><code class="java">public static <T extend String> void genericMethod(T t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>Will be converted to following at compile time:<br />
<pre><code class="java">public static void genericMethod(String t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>The post <a href="https://www.manishsanger.com/type-erasure-java-generics/">Type Erasure &#8211; Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/type-erasure-java-generics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/type-erasure-Java-generics.png" length="15679" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/type-erasure-Java-generics.png" width="703" height="160" medium="image" type="image/png"/>	</item>
		<item>
		<title>Java Generics</title>
		<link>https://www.manishsanger.com/java-generics/</link>
					<comments>https://www.manishsanger.com/java-generics/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 20 Mar 2018 08:34:44 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[bounded-type-parameter]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[generics]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=334</guid>

					<description><![CDATA[<p>Generics are a feature of generic programming which was introduced in Java 5. This allows a type or method to work with various object types while providing compile-time type safety. For example, collection framework supports generics. We can use Hashset, ArrayList, HashMap etc. to store various type of objects, and while retrieving the data we [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/java-generics/">Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Generics are a feature of generic programming which was introduced in Java 5. This allows a type or method to work with various object types while providing compile-time type safety. For example, collection framework supports generics. We can use Hashset, ArrayList, HashMap etc. to store various type of objects, and while retrieving the data we don&#8217;t need to type cast.<br />
In Java 5, java rewrote the collection framework to incorporate the generics.</p>
<p>Here is an example of ArrayList without using generics:</p>
<pre><code class="java">List names = new ArrayList();<br />
names.add("Manish");<br />
String name = (String) names.get(0); //Type casting when retrieving the element from the array list</p>
<p>Integer number = (Integer) names.get(0); //Run-time error, ClassCastException will be thrown.<br />
</code></pre>
<p>When we use the ArrayList without generics, will have to type cast when we retrieve the element from the ArrayList, as the program doesn&#8217;t know the type of element stored in ArrayList. Also, when we try to type cast the element in the wrong way as I did in the code above, trying to type cast the element to Integer it will throw run-time ClassCastException error. Without generics, we only get the errors at the run-time not at compile time.</p>
<p>We can rewrite the code using generics as follows:</p>
<pre><code class="java">List<String> names = new ArrayList();<br />
names.add("Manish");<br />
String name = names.get(0); //No type casting is required.<br />
</code></pre>
<p><b>Creating custom Java generic Class:</b><br />
We can create our own generic class. A generic type is a class or interface that is parameterized over types, we use angle bracket (<>) to specify the type parameter.<br />
Note: Type argument can&#8217;t be of a primitive type.</p>
<pre><code class="java">public class GenericExample<T> {<br />
    private T t;<br />
    public T getT() {<br />
        return t;<br />
    }<br />
    public void setT(T t) {<br />
        this.t = t;<br />
    }<br />
}</p>
<p>class GenericTest{<br />
    public static void main(String[] args) {<br />
        //Instance with String type<br />
        GenericExample<String> genericExample = new GenericExample<>();<br />
        genericExample.setT("Test");</p>
<p>        //Instance with Integer type<br />
        GenericExample<Integer> genericExample1 = new GenericExample<>();<br />
        genericExample1.setT(100);</p>
<p>        //Type argument can't be primitive type.<br />
    }<br />
}<br />
</code></pre>
<p><b>Class with multiple type parameters:</b></p>
<pre><code class="java">public class GenericExample<T, U> {<br />
    private T t;<br />
    private U u;</p>
<p>    public GenericExample(T t, U u) {<br />
        this.t = t;<br />
        this.u = u;<br />
    }<br />
}</p>
<p>class GenericTest{<br />
    public static void main(String[] args) {<br />
        //Instance with String type<br />
        GenericExample<String, Integer> genericExample = new GenericExample<>("Test", 100);<br />
    }<br />
}<br />
</code></pre>
<p><b>Generic Method</b><br />
We can also create the generic method or constructor, no need to parameterize the whole class.</p>
<pre><code class="java">class GenericMethodTest{<br />
    static <T> void genericMethod(T t){<br />
        System.out.println(t);<br />
    }<br />
    public static void main(String[] args) {<br />
        GenericMethodTest.<String>genericMethod("Test");<br />
        GenericMethodTest.genericMethod("Test 2"); //Using type interface<br />
    }<br />
}<br />
</code></pre>
<p>In the above code, we can specify the type when calling the method or can just call like a normal method without specifying any type, JVM will do it for you. This feature is called type interface.</p>
<p><b>Java generics bounded type parameters:</b><br />
If we want to restrict the type of objects which can be used as parametrized type:<br />
<pre><code class="java">class GenericBound<T extends List> {<br />
    private T t;</p>
<p>    public GenericBound(T t) {<br />
        this.t = t;<br />
    }<br />
}<br />
</code></pre>
<p><b>Java generic type naming convention (Best practices)</b><br />
As per the Java best practices, type parameter should be single and uppercase letters. Following are the commonly used type parameters:</p>
<ul>
<li>T &#8211; Type</li>
<li>E &#8211; Element (Used extensively in collection framework)</li>
<li>N &#8211; Number</li>
<li>K &#8211; Key</li>
<li>V &#8211; Value</li>
<li>S,U,V etc. &#8211; 2nd, 3rd, 4th types</li>
</ul>
<p>The post <a href="https://www.manishsanger.com/java-generics/">Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/java-generics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/Java-generics.png" length="15016" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/Java-generics.png" width="731" height="125" medium="image" type="image/png"/>	</item>
		<item>
		<title>Java Try with Resources</title>
		<link>https://www.manishsanger.com/try-with-resources/</link>
					<comments>https://www.manishsanger.com/try-with-resources/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Mon, 19 Feb 2018 11:50:16 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java 7]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[try-with-resources]]></category>
		<category><![CDATA[file-handling]]></category>
		<category><![CDATA[Development]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=320</guid>

					<description><![CDATA[<p>A resource is an object that must be closed once the program is finished or done using it, for example, file resource, JDBC database connection resource, socket connection resource etc. Prior to Java 7, there was no auto resource management, we open the resource in a try block and close the resource in finally block. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/try-with-resources/">Java Try with Resources</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A resource is an object that must be closed once the program is finished or done using it, for example, file resource, JDBC database connection resource, socket connection resource etc.</p>
<p>Prior to Java 7, there was no auto resource management, we open the resource in a try block and close the resource in finally block. For example:</p>
<pre><code class="java">try{<br />
//open resources<br />
}catch(IOException){<br />
//Exception handling<br />
}finally{<br />
//close resource<br />
}<br />
</code></pre>
<p>In the above approach there were few drawbacks:</p>
<ol>
<li>It causes memory leaks and performance issue if the developer forgot to close the resource.</li>
<li>Finally block will always be executed, it doesn&#8217;t matter if the exception is thrown from the try block. It means, it tries to close the resource in finally block, even if it doesn&#8217;t exist which again cause an exception to be thrown from finally block.</li>
<li>Exception thrown from finally block will be propagated up the call stack, though exception from try block is more relevant.</li>
</ol>
<p><b><u>try-with-resource</u></b><br />
In Java 7, a new approach called &#8220;try-with-resources&#8221; is introduced for auto resource management. In this when try block finishes, it automatically closes the resource.</p>
<p>Here is an example for try-with-resource construct:<br />
<pre><code class="java">private static void readFile() throws IOException {<br />
try(FileInputStream input = new FileInputStream("file.txt")) {<br />
int data = input.read();<br />
while(data != -1){<br />
System.out.print((char) data);<br />
data = input.read();<br />
}<br />
}<br />
}<br />
</code></pre>
<p>&nbsp;</p>
<p><b>try-with-resource using multiple resources</b><br />
We can use multiple resources in try-with-resource block, it will automatically close both the resources when program finish executing try block.</p>
<pre><code class="java">private static void readFile() throws IOException {<br />
try(  FileInputStream input = new FileInputStream("file.txt");<br />
BufferedInputStream bufferedInput = new BufferedInputStream(input)<br />
) {<br />
int data = bufferedInput.read();<br />
while(data != -1){<br />
System.out.print((char) data);<br />
data = bufferedInput.read();<br />
}<br />
}<br />
}<br />
</code></pre>
<p>The resources are closed in reverse order of they are declared inside the try. <i>BufferedInputStream</i> will be closed first, then <i>FileInputStream</i>.<br />
&nbsp;<br />
<b><u>AutoCloseable Custom implementation</u></b><br />
Java 7 has introduced an interface <b><i>java.lang.AutoCloseable</i></b>. To use any resource in try-with-resource block, it must implement the AutoCloseable interface. We can also implement <i>java.lang.AutoCloseable</i> interface in our own classes and use them with the try-with-resources construct.<br />
<i>AutoCloseable </i>interface only has one method class <i>close()</i>. Here is the <i>AutoCloseable</i> interface:</p>
<pre><code class="java">public interface AutoCloseable {<br />
public void close() throws Exception;<br />
}<br />
</code></pre>
<p>&nbsp;<br />
<b><u>Exception handling with try-with-resource:</u></b><br />
If one or more exceptions are thrown by try block in try-with-resources, the exceptions thrown are <b><i>suppressed exception</i></b>.<br />
Java added an constructor and two methods in <b>Throwable</b> class to deal with suppressed exceptions. We can get these exceptions by using the <b><i>getSuppress()</i></b> method of <b>Throwable</b> class.</p>
<p><b><u>Advantages of using try-with-resource construct:</u></b></p>
<ol>
<li>Auto resource management.</li>
<li>More readable code.</li>
<li>No need of finally block just to close the resource.</li>
<li>Meaning &amp; relevant exceptions.</li>
</ol>
<p>The post <a href="https://www.manishsanger.com/try-with-resources/">Java Try with Resources</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/try-with-resources/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/02/Java-try-with-resource.png" length="34462" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/02/Java-try-with-resource.png" width="757" height="232" medium="image" type="image/png"/>	</item>
		<item>
		<title>Volatile Modifier: Java Multi-threading</title>
		<link>https://www.manishsanger.com/volatile-modifier/</link>
					<comments>https://www.manishsanger.com/volatile-modifier/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Wed, 07 Feb 2018 13:21:14 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[multi-threading]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[thread-safe]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=294</guid>

					<description><![CDATA[<p>In Java volatile keyword is used to guarantee memory visibility of a variable. When a variable is marked as volatile, it will be stored in main memory. Every read &#38; write is performed on main memory instead of CPU cache. In case of without volatile instance variable, read/write are always performed on CPU cache not [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/volatile-modifier/">Volatile Modifier: Java Multi-threading</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In Java <strong>volatile</strong> keyword is used to guarantee memory visibility of a variable. When a variable is marked as volatile, it will be stored in main memory. Every read &amp; write is performed on main memory instead of CPU cache.</p>
<p>In case of without volatile instance variable, read/write are always performed on CPU cache not directly on main memory, in such cases when multiple threads are performing read/write on multiprocessor system there are possibilities that the variable is updated in CPU cache but not in main memory as JVM take some time to push changes to main memory and some threads may get non-updated value (by other thread) from their own CPU cache. Remember, every thread in Java has it&#8217;s own thread local stack at runtime.</p>
<p>Volatile keyword guarantees visibility of changes across threads. Using volatile is a way to make your class thread-safe like synchronized and atomic wrapper. It means the volatile variable can be used by multiple threads for read/write at the same time without any problem.</p>
<p><span style="text-decoration: underline;"><strong>Synchronize vs Volatile</strong></span></p>
<p>In concurrency there are 2 important concepts:<br />
1. Atomicity (Mutual Exclusion): It means only one thread can update the value, by executing critical section.<br />
2. Visibility: It means that value updated by one thread to shared data is visible to other thread.</p>
<p>Synchronized keyword guarantees both atomicity and Visibility. In synchronized code block which updates the value, only one thread can enter the code block (critical section) and the update will be reflected in main memory, all the other thread will be blocked and put to sleep.</p>
<p>In some cases, we may only need visibility, not atomicity, in those cases volatile can be used, as using synchronized will cause performance issues because it allows only one thread to work other will be blocked.</p>
<p><span style="text-decoration: underline;"><strong>Use Cases:</strong></span><br />
In Java volatile usage is limited to very restricted use cases. I tried to capture most of the use cases here:<br />
1. Boolean flag<br />
A most common use case of volatile is a simple boolean flag, setting up the value to true/false in one thread and multiple threads are accessing that variable, and where write doesn&#8217;t depend upon existing/current value. Ex: terminating a thread based on flag value.<br />
2. One thread writes and other reads<br />
Volatile can be used when only one thread is writing the value and other only reading its value.<br />
3. Double-checked locking mechanism<br />
Used often in Singleton design pattern. In this, the singleton object needs to be declared volatile.</p>
<p><span style="text-decoration: underline;"><strong>Performance:</strong></span><br />
As volatile write/read are performed on the main memory, read/write on main memory is more expensive than accessing it from CPU cache.<br />
Accessing volatile variable also prevent instruction reordering which is a normal performance enhancement technique.</p>
<p>The post <a href="https://www.manishsanger.com/volatile-modifier/">Volatile Modifier: Java Multi-threading</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/volatile-modifier/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
