<?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>Programming Archives - Manish Sanger</title>
	<atom:link href="https://www.manishsanger.com/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.manishsanger.com/programming/</link>
	<description>Java, J2EE, Spring Framework, application security,big data,database,design patterns,hibernate,j2ee,java,jdbc,micro-services,mongodb,multithreading,nosql</description>
	<lastBuildDate>Wed, 09 May 2018 06:57:45 +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>PermGen to Metaspace in Java 8</title>
		<link>https://www.manishsanger.com/permgen-to-metaspace-in-java-8/</link>
					<comments>https://www.manishsanger.com/permgen-to-metaspace-in-java-8/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 08 May 2018 14:02:04 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=380</guid>

					<description><![CDATA[<p>In Java 8, PermGen space on the heap is replaced by Metaspace on native memory. The main difference between them is, Metaspace by default auto increases its size up to the memory provided by the Operating System, while PermGen always had a fixed maximum size. So, there will be fewer chances to get the OutOfMemoryError. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/permgen-to-metaspace-in-java-8/">PermGen to Metaspace in Java 8</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In Java 8, <strong>PermGen</strong> space on the heap is replaced by <strong>Metaspace</strong> on native memory. The main difference between them is, <strong>Metaspace</strong> by default auto increases its size up to the memory provided by the Operating System, while <strong>PermGen</strong> always had a fixed maximum size. So, there will be fewer chances to get the <strong>OutOfMemoryError</strong>.<br />
When <strong>PermGen</strong> was initially introduced there was no dynamic class loading/unloading, so when the class was loaded it was there in <strong>PermGen</strong> until JVM shuts down. These days classes may be loaded/unloaded during the lifespan of JVM, so <strong>Metaspace</strong> makes more sense for the area where metadata is stored.</p>
<p><strong>Difference between PermGen and Metaspace:</strong></p>
<ul>
<li style="list-style-type: none;">
<ul>
<li><strong>PermGen</strong> had a fixed maximum size by default, where <strong>Metaspace</strong> size auto increases by default.</li>
<li><strong>PermGen</strong> max size can be changed using <b>-XX:MaxPermSize</b> option and <strong>Metaspace</strong> maximum size can also be fixed using <b>XX:MaxMetaspaceSize</b>.</li>
<li><strong>PermGen</strong> has comparatively inefficient garbage collection &#8211; frequent pauses and no concurrent deallocation. Where, <strong>Metaspace</strong> has comparatively efficient garbage collection &#8211; deallocated class data concurrently and not during GC pause.</li>
</ul>
</li>
</ul>
<p><strong>Metaspace garbage collection</strong></p>
<ol>
<li>Garbage collection of the dead classes and classloaders is triggered once the class metadata usage reaches the “<strong>MaxMetaspaceSize</strong>”.</li>
<li>Proper monitoring &amp; tuning of the Metaspace will obviously be required in order to limit the frequency or delay of such garbage collections. Excessive Metaspace garbage collections may be a symptom of classes, classloader memory leak or inadequate sizing for your application.</li>
</ol>
<p>There were few new flags added in Java 8 for Metaspace:</p>
<ol>
<li><b>-XX:MetaspaceSize=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the initial amount of space (initial high-water mark) allocated (in bytes)for class metadata that may induce a garbage collection to unload classes. After the amount of first high-water mark reached, the next high-water mark is managed by the garbage collector.</li>
<li><b>-XX:MaxMetaspaceSize=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the maximum amount of space allocated for class metadata (in bytes). This flag can be used to limit the amount of space allocated for class metadata, by default, there is no limit.</li>
<li><b>-XX:MinMetaspaceFreeRatio=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the minimum percentage of class metadata capacity free after a GC to avoid an increase in the amount of space (high-water-mark) allocated for class metadata that will induce a garbage collection.</li>
<li><b>-XX:MaxMetaspaceFreeRatio=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the maximum percentage of class metadata capacity free after a GC to avoid a reduction in the amount of space (high-water-mark) allocated for class metadata that will induce a garbage collection.</li>
</ol>
<p><b><i>Note:</i></b> Metaspace size auto increases in native memory as required to load class metadata if not restricted with <b>-XX:MaxMetaspaceSize<b>, It can bring down the whole server if not restricted. Be cautious to define this limit, so that we can avoid memory wastage.</p>
<p>The post <a href="https://www.manishsanger.com/permgen-to-metaspace-in-java-8/">PermGen to Metaspace in Java 8</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/permgen-to-metaspace-in-java-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Garbage Collection in Java</title>
		<link>https://www.manishsanger.com/garbage-collection-in-java/</link>
					<comments>https://www.manishsanger.com/garbage-collection-in-java/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 08 May 2018 13:39:54 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=377</guid>

					<description><![CDATA[<p>What is Garbage collection? The process of destroying unused/unreferenced objects are called garbage collection. Java garbage collection is the process by which Java programs performs automatic memory management. When Java programs run on the JVM, objects are created on the heap. When the object is no longer required, garbage collector find those unused objects and [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/garbage-collection-in-java/">Garbage Collection in Java</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><b>What is Garbage collection?</b></p>
<p>The process of destroying unused/unreferenced objects are called garbage collection. Java garbage collection is the process by which Java programs performs automatic memory management.</p>
<p>When Java programs run on the JVM, objects are created on the heap. When the object is no longer required, garbage collector find those unused objects and remove them to free up memory for reuse.</p>
<p><b>How Garbage Collection work?</b></p>
<p>Java Garbage collection is an automatic process, we don&#8217;t need to explicitly mark objects for deletion. Garbage collection implementation lives in the JVM. We can only request JVM for garbage collection, by using <b>System.gc()</b> and <b>Runtime.getRunTime.gc()</b>, but we can&#8217;t force it.</p>
<p>Different JVM&#8217;s have their own way of garbage collection implementation, Oracle&#8217;s HotSpot is the most common JVM which offers the robust and mature set of garbage collection options. HotSpot has multiple garbage collectors that are optimized for various use cases, but all follow the same basic principle.</p>
<p>In the first step, all the live objects are tracked and marked as alive. Everything else is eligible for garbage collection.</p>
<p>In the second step, eligible objects for garbage collection are deleted from the heap. Optionally memory can be compacted, so that remaining objects are in a contiguous block at the start of the heap. The memory compacting process makes it easier to allocate memory to new objects sequentially after the block of memory allocated to existing objects.</p>
<p>All objects are allocated on heap memory are managed by JVM. As long as the object being referenced, the JVM considers it alive.</p>
<p>All HotSpot garbage collectors implement <b>Generational Garbage Collection</b> strategy, which categorizes objects by their age. As per the Generational Garbage collection strategy, it believes that most objects are short-lived and are eligible for garbage collection as soon as they are created.</p>
<p><strong>The heap is divided into three sections:</strong></p>
<div id="attachment_378" style="width: 505px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/05/Garbage-collection.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-378" class="size-full wp-image-378" src="https://www.manishsanger.com/wp-content/uploads/2018/05/Garbage-collection.png" alt="Garbage Collection in Java" width="495" height="338" srcset="https://www.manishsanger.com/wp-content/uploads/2018/05/Garbage-collection.png 495w, https://www.manishsanger.com/wp-content/uploads/2018/05/Garbage-collection-300x205.png 300w" sizes="(max-width: 495px) 100vw, 495px" /></a><p id="caption-attachment-378" class="wp-caption-text">Garbage Collection in Java</p></div>
<p>&nbsp;</p>
<ul>
<li><b>Young Generation:</b><br />
Newly created objects start in Young generation. The young generation is further subdivided into Eden and two survivors (S1, S2) spaces. Eden is the space where are the newly created objects start and moved to Survivor space after one GC cycle. When objects are garbage collected from Young generation space are called minor GC event.</li>
<li><b>Old Generation:</b><br />
Objects that are long-lived are moved from Young Generation to Old Generation. When objects from Old generation are garbage collected are major GC event.</li>
<li><b>Permanent Generation (PermGen):</b><br />
Metadata (classes and methods) are stored in <b>Permanent Generation</b>. Classes that are no longer required may be garbage collected from Permanent Generation.</li>
</ul>
<p>In Java 8, <b>PermGen</b> is replaced by  <b>Metaspace. Metaspace</b> now uses native memory for the representation of class metadata. It is not mandatory now to define <b>PermSize</b> and <b>MaxPermSize. </b>So, when memory usage increases you will not get the OutOfMemoryError, reserve native memory is increased to full-fill the memory usage. To know more about <b>Metaspace</b>, <a href="https://www.manishsanger.com/permgen-to-metaspace-in-java-8/" target="_blank" rel="noopener">read this article.</a></p>
<p>During a full garbage collection event, unused objects in all generations are garbage collected.</p>
<p><span style="text-decoration: underline;"><b>Garbage Collection Roots (GC Roots):</b></span></p>
<p><b>GC Roots</b> are basically stack variable/pointers that hold the reference to objects in Heap and accessible directly outside from the heap. Every object must have one or more root objects, as long as the application can reach those roots, the whole object tree is reachable.</p>
<p>There is four kind of GC roots in Java:</p>
<ul>
<li><b>Local variables:</b> They are not a real object virtual reference and kept alive on the stack of the thread. For all intents and purposes, local variables are GC Roots.</li>
<li><b>Active Java Thread:</b> They are always live objects and are considered GC roots, this is also important for thread local variables.</li>
<li><b>Static Variables:</b> They are referenced by their classes, which makes GC roots. Classes themselves can be garbage collected which also removes all referenced static variables.</li>
<li><b>JNI References</b>: These are the java objects which gets created by native code as part of the  JNI call. Objects created are treated specially because the JVM does not know if it is being referenced by native code or not.</li>
</ul>
<p>A simple java application has the following GC roots:</p>
<ol>
<li>The local variable in the main method.</li>
<li>The main thread</li>
<li>Static variables of the main class.</li>
</ol>
<p><span style="text-decoration: underline;"><b>Mark and Sweep Algorithm:</b></span></p>
<p>To determine which objects are no longer in use, the JVM intermittently runs <b>mark and sweep algorithm</b>. It is a 2 step process:</p>
<ol>
<li>The algorithm traverses all the object references, starting with the GC roots and marks every object found alive.</li>
<li>Heap memory which is not occupied by marked objects is reclaimed and marked as free.</li>
</ol>
<p>HotSpot JVM has four garbage collectors:</p>
<ul>
<li><b>Serial:</b> Garbage collection events are performed serially in one thread. Memory compaction is performed after each garbage collection event.</li>
<li><b>Parallel:</b> Multiple threads are used for minor garbage collection. A single thread is used for major garbage collections and Old Generation memory compaction. Alternatively Parallel Old variant uses multiple threads for major garbage collection and Old Generation Compaction.</li>
<li><b>Concurrent Mark and Sweep (CMS):</b> Multiple threads are used for minor garbage collection using the same algorithm as parallel. Major garbage collection is also multi-threaded like Parallel Old, but CMS runs concurrently with the application. This means that garbage collection is not explicitly stopping the application threads to perform GC. No compaction is performed.</li>
<li><b>G1 (Garbage first):</b> This newest garbage collector is intended as a replacement for CMS. It is parallel and concurrent like CMS. The Garbage-First (G1) collector is a server-style garbage collector, targeted for multi-processor machines with large memories. It meets garbage collection (GC) pause time goals with a high probability while achieving high throughput.</li>
</ul>
<p>The post <a href="https://www.manishsanger.com/garbage-collection-in-java/">Garbage Collection in Java</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/garbage-collection-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/05/Garbage-collection.png" length="15263" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/05/Garbage-collection.png" width="495" height="338" medium="image" type="image/png"/>	</item>
		<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[microservices]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[java]]></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 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 loading="lazy" 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="auto, (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[microservices]]></category>
		<category><![CDATA[java]]></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[java]]></category>
		<category><![CDATA[exception]]></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>Wildcard &#8211; Java Generics</title>
		<link>https://www.manishsanger.com/wildcard-java-generics/</link>
					<comments>https://www.manishsanger.com/wildcard-java-generics/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 20 Mar 2018 08:44:00 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=338</guid>

					<description><![CDATA[<p>A wildcard can be used as a type of a parameter, field, local variable, and return type. Question mark (?) wildcard in generics and it represents the unknown type. Unbounded wildcard When we want our generic type to be working with all types, an unbounded wildcard can be used. For example: In the above example [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/wildcard-java-generics/">Wildcard &#8211; Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A wildcard can be used as a type of a parameter, field, local variable, and return type. Question mark (?) wildcard in generics and it represents the unknown type.</p>
<p><b>Unbounded wildcard</b><br />
When we want our generic type to be working with all types, an unbounded wildcard can be used.<br />
For example:<br />
<pre><code class="java">class UnboundWildcard {<br />
    public static void UnboundWildcardPrint(List<?> list) {<br />
        list.forEach(listElement->{<br />
            System.out.println(listElement);<br />
        });<br />
    }<br />
    public static void main(String[] args) {<br />
        List<String> list = new ArrayList<>();<br />
        list.add("A");<br />
        list.add("B");<br />
        list.add("C");<br />
        UnboundWildcardPrint(list);<br />
        List<Integer> numbers = new ArrayList<>();<br />
        numbers.add(10);<br />
        numbers.add(50);<br />
        numbers.add(100);<br />
        UnboundWildcardPrint(numbers);<br />
    }<br />
}<br />
</code></pre>
<p>In the above example list parameter is provided as List<String> and List<Integer>, it can be of any other type of Object List argument to UnboundWildcardPrint method.<br />
Unbounded wildcard is equivalent to <? Extends Object>.</p>
<p><b>Upper Bounded wildcard</b><br />
This is useful when we want to relax the restriction on the type of parameter in a method. For example, we want to write a method, that works with List<Integer>, List<Double>, List<Long>, and List<Number>. We can do this by using an upper bound wildcard as follows:</p>
<pre><code class="java">Public static void sum(List<? extends Number>)<br />
</code></pre>
<p><b>Lower Bound wildcard:</b><br />
This is useful when we want to restrict the type of parameter in a method to it&#8217;s lower bound and it&#8217;s super class.<br />
For example:<br />
<pre><code class="java">public static void sumIntegers(List<? super Integer> list)<br />
</code></pre>
<p>In the above example, we can only pass Integer or Number (Super class of Integer). We can&#8217;t pass Double or Long, as they aren&#8217;t the Super class of Integer.</p>
<p>The post <a href="https://www.manishsanger.com/wildcard-java-generics/">Wildcard &#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/wildcard-java-generics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/wildcard-Java-generics.png" length="10414" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/wildcard-Java-generics.png" width="703" height="150" 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[Development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[bounded-type-parameter]]></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[Development]]></category>
		<category><![CDATA[Java 7]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[try-with-resources]]></category>
		<category><![CDATA[file-handling]]></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>
	</channel>
</rss>
