tag:blogger.com,1999:blog-62534722511727706022024-03-21T01:11:56.423-07:00Java In DepthPrabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.comBlogger30125tag:blogger.com,1999:blog-6253472251172770602.post-87443596754156655382020-06-24T09:21:00.003-07:002020-06-24T23:32:32.620-07:00Power of Lambda - II<font face="inherit">There is a very common interview question or you can say common requirement in our daily coding life we come across.</font><div><i><font face="inherit"><br /></font></i></div><div><i><font face="inherit">"Write a Java program to count the occurrence of each character in a string"</font></i></div><div><i><font face="inherit"><br /></font></i></div><div><font face="inherit">There are various type of logics to achieve this</font></div><div><ul style="text-align: left;"><li><font face="inherit">using array</font></li><li><font face="inherit">using Java maps etc...</font></li></ul><font face="inherit">But here I am going to demonstrate how it can be achieved in a smarter way using the power of lambda.</font></div><div><pre style="background-color: #292a30; color: #dfdfe0; font-family: "jetbrains mono", monospace; font-size: 9.8pt;"><span style="color: #82e6ff;">String </span><span style="color: #fcfcfc;">statement </span>= <span style="color: #ff806c;">"A quick brown fox jumps over the lazy dog!"</span>;<br /><span style="color: #f97bb0; font-weight: bold;">final </span><span style="color: #65dfff;">Map</span><span style="color: #ffa245; font-style: italic;"><</span><span style="color: #82e6ff;">Character</span>, <span style="color: #82e6ff;">Integer</span><span style="color: #ffa245; font-style: italic;">> </span><span style="color: #fcfcfc;">charOccurrenceMap </span>= <span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">HashMap</span><span style="color: #ffa245; font-style: italic;"><>()</span>;<br /><span style="color: #fcfcfc;">statement</span>.<span style="color: #75c2b3;">chars</span><span style="color: #ffa245; font-style: italic;">()<br /></span><span style="color: #ffa245; font-style: italic;"> </span>.<span style="color: #75c2b3;">forEach</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">ch </span>-> <span style="color: #b389c5;">charOccurrenceMap<br /></span><span style="color: #b389c5;"> </span>.<span style="color: #75c2b3;">merge</span><span style="color: #ffa245; font-style: italic;">((</span><span style="color: #f97bb0; font-weight: bold;">char</span><span style="color: #ffa245; font-style: italic;">)</span><span style="color: #fcfcfc;">ch</span>, <span style="color: #d7c781;">1</span>, <span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">prevValue</span>, <span style="color: #fcfcfc;">value</span><span style="color: #ffa245; font-style: italic;">) </span>-> <span style="color: #fcfcfc;">prevValue </span>+ <span style="color: #fcfcfc;">value</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /><span style="color: #82e6ff;">System</span>.<span style="color: #49b0ce; font-style: italic;">out</span>.<span style="color: #75c2b3;">println</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">charOccurrenceMap</span><span style="color: #ffa245; font-style: italic;">)</span>;</pre></div><div><pre style="font-family: "jetbrains mono", monospace; font-size: 9.8pt;"><b style="background-color: white; font-size: 9.8pt;"><u>Output</u></b></pre><pre><font face="" style="background-color: white; font-size: 13.0667px;">{A=1, =8, !=1, a=1, b=1, c=1, d=1, e=2, f=1, g=1, h=1, i=1, j=1, k=1, l=1, m=1, n=1, o=4, </font></pre><pre><font face="" style="background-color: white; font-size: 13.0667px;">p=1, q=1, </font>r=2, s=1, t=1, u=2, v=1, w=1, x=1, y=1, z=1}</pre><h4 style="text-align: left;"><font face="inherit" style="background-color: white;"><b>Realtime Example</b></font></h4><pre><font face="inherit" style="background-color: white; font-size: 13.0667px;"><i>"Let's you have a collection of customer requests and </i></font><i style="font-family: inherit; font-size: 13.0667px;">want to count number of </i></pre><pre><i style="font-family: inherit; font-size: 13.0667px;">requests initiated by each account"</i></pre><pre><pre style="background-color: #292a30; color: #dfdfe0; font-family: "jetbrains mono", monospace; font-size: 9.8pt;"><span style="color: #f97bb0; font-weight: bold;">class </span><span style="color: #82e6ff;">CustomerRequest </span><span style="color: #ffa245; font-style: italic;">{<br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #f97bb0; font-weight: bold;">long </span><span style="color: #49b0ce;">accNo</span>;<br /> <span style="color: #82e6ff;">String </span><span style="color: #49b0ce;">reqPayload</span>;<br /> <span style="color: #7f8c99;">// some other details<br /></span><span style="color: #7f8c99;"> </span><span style="color: #f97bb0; font-weight: bold;">public </span><span style="color: #75c2b3;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #f97bb0; font-weight: bold;">long </span><span style="color: #fcfcfc;">accNo</span>, <span style="color: #82e6ff;">String </span><span style="color: #fcfcfc;">reqPayload</span><span style="color: #ffa245; font-style: italic;">) {<br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #f97bb0; font-weight: bold;">this</span>.<span style="color: #49b0ce;">accNo </span>= <span style="color: #fcfcfc;">accNo</span>;<br /> <span style="color: #f97bb0; font-weight: bold;">this</span>.<span style="color: #49b0ce;">reqPayload </span>= <span style="color: #fcfcfc;">reqPayload</span>;<br /> <span style="color: #ffa245; font-style: italic;">}<br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #7f8c99;">//getter and setter<br /></span><span style="color: #ffa245; font-style: italic;">}</span></pre><pre><pre style="background-color: #292a30; color: #dfdfe0; font-family: "jetbrains mono", monospace; font-size: 9.8pt;"><span style="color: #f97bb0; font-weight: bold;">public class </span><span style="color: #82e6ff;">Main </span><span style="color: #ffa245; font-style: italic;">{<br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #f97bb0; font-weight: bold;">public static void </span><span style="color: #75c2b3;">main</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #82e6ff;">String</span><span style="color: #ffa245; font-style: italic;">[] </span><span style="color: #fcfcfc;">args</span><span style="color: #ffa245; font-style: italic;">) {<br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #65dfff;">List</span><span style="color: #ffa245; font-style: italic;"><</span><span style="color: #82e6ff;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">> </span><span style="color: #fcfcfc;">requestList </span>= <span style="font-style: italic;">generateDummyCustomerRequests</span><span style="color: #ffa245; font-style: italic;">()</span>;<br /> <span style="color: #f97bb0; font-weight: bold;">final </span><span style="color: #82e6ff;">HashMap</span><span style="color: #ffa245; font-style: italic;"><</span><span style="color: #82e6ff;">Long</span>, <span style="color: #82e6ff;">Integer</span><span style="color: #ffa245; font-style: italic;">> </span><span style="color: #fcfcfc;">requestCountMap </span>= <span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">HashMap</span><span style="color: #ffa245; font-style: italic;"><>()</span>;<br /> <span style="color: #fcfcfc;">requestList<br /></span><span style="color: #fcfcfc;"> </span>.<span style="color: #75c2b3;">stream</span><span style="color: #ffa245; font-style: italic;">()<br /></span><span style="color: #ffa245; font-style: italic;"> </span>.<span style="color: #75c2b3;">map</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #82e6ff;">CustomerRequest</span>::<span style="color: #75c2b3;">getAccNo</span><span style="color: #ffa245; font-style: italic;">)<br /></span><span style="color: #ffa245; font-style: italic;"> </span>.<span style="color: #75c2b3;">forEach</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">accNumber </span>-> <span style="color: #b389c5;">requestCountMap<br /></span><span style="color: #b389c5;"> </span>.<span style="color: #75c2b3;">merge</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">accNumber</span>, <span style="color: #d7c781;">1</span>, <span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">prevCount</span>, <span style="color: #fcfcfc;">value</span><span style="color: #ffa245; font-style: italic;">) </span>-> <span style="color: #fcfcfc;">prevCount </span>+ <span style="color: #d7c781;">1</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /> <span style="color: #82e6ff;">System</span>.<span style="color: #49b0ce; font-style: italic;">out</span>.<span style="color: #75c2b3;">println</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #fcfcfc;">requestCountMap</span><span style="color: #ffa245; font-style: italic;">)</span>;<br /> <span style="color: #ffa245; font-style: italic;">}<br /></span><span style="color: #ffa245; font-style: italic;"> <br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #7f8c99;">// this is a helper method to build dummy customer requests<br /></span><span style="color: #7f8c99;"> </span><span style="color: #f97bb0; font-weight: bold;">private static </span><span style="color: #65dfff;">List</span><span style="color: #ffa245; font-style: italic;"><</span><span style="color: #82e6ff;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">> </span><span style="color: #75c2b3;">generateDummyCustomerRequests</span><span style="color: #ffa245; font-style: italic;">() {<br /></span><span style="color: #ffa245; font-style: italic;"> </span><span style="color: #f97bb0; font-weight: bold;">final </span><span style="color: #82e6ff;">ArrayList</span><span style="color: #ffa245; font-style: italic;"><</span><span style="color: #82e6ff;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">> </span><span style="color: #fcfcfc;">customerRequests </span>= <span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">ArrayList</span><span style="color: #ffa245; font-style: italic;"><>()</span>;<br /> <span style="color: #fcfcfc;">customerRequests</span>.<span style="color: #75c2b3;">add</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #d7c781;">123</span>, <span style="color: #ff806c;">"payload 1"</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /> <span style="color: #fcfcfc;">customerRequests</span>.<span style="color: #75c2b3;">add</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #d7c781;">345</span>, <span style="color: #ff806c;">"payload 2"</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /> <span style="color: #fcfcfc;">customerRequests</span>.<span style="color: #75c2b3;">add</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #d7c781;">123</span>, <span style="color: #ff806c;">"payload 3"</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /> <span style="color: #fcfcfc;">customerRequests</span>.<span style="color: #75c2b3;">add</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #d7c781;">456</span>, <span style="color: #ff806c;">"payload 4"</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /> <span style="color: #fcfcfc;">customerRequests</span>.<span style="color: #75c2b3;">add</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #f97bb0; font-weight: bold;">new </span><span style="color: #75c2b3;">CustomerRequest</span><span style="color: #ffa245; font-style: italic;">(</span><span style="color: #d7c781;">345</span>, <span style="color: #ff806c;">"payload 5"</span><span style="color: #ffa245; font-style: italic;">))</span>;<br /> <span style="color: #f97bb0; font-weight: bold;">return </span><span style="color: #fcfcfc;">customerRequests</span>;<br /> <span style="color: #ffa245; font-style: italic;">}<br /></span><span style="color: #ffa245; font-style: italic;">}</span></pre><pre style="font-family: "jetbrains mono", monospace; font-size: 9.8pt;"><span style="background-color: white; font-style: italic;"><b><u>Output</u></b></span></pre><pre><font face=""><span style="background-color: white; font-size: 13.0667px;">{456=1, 345=2, 123=2}<font color="#dfdfe0">
</font></span></font></pre><pre><font color="#dfdfe0" face=""><a name='more'></a></font></pre><pre><span style="background-color: white; font-size: 13.0667px;"><font face="inherit">Here is what java documentation of Map.merge() method says:</font></span></pre><pre><font color="#3367d6"><span style="background-color: white; font-size: 13.0667px;"><font><i>If the specified key is not already associated with a value or is
associated with null, associates it with the given non-null value.
Otherwise, replaces the associated value with the results of the given
remapping function, or removes if the result is {@code null}. This
method may be of use when combining multiple mapped values for a key.
For example, to either create or append a {@code String msg} to a
value mapping: </i></font></span><span style="font-size: 13.0667px;"><i>map.merge(key, msg, String::concat)</i></span></font></pre><pre><span style="font-size: 13.0667px;"><font face="inherit">How it works internally is:</font></span></pre><pre><font color="#3367d6" style="font-size: 13.0667px;"><i>V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if (newValue == null)
map.remove(key);
else
map.put(key, newValue);</i></font></pre><pre><span><!--more--></span></pre><pre><span style="font-size: 13.0667px;">I hope it helps to understand how powerful is Java lambda and stream API. Please start </span></pre><pre><span style="font-size: 13.0667px;">using in your daily coding. Please feel free to share your comment and feedback.</span></pre></pre></pre></div>Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-26271965298250991842019-08-07T08:09:00.002-07:002019-08-07T08:30:57.120-07:00Best practices while parsing downstream response with enum value<div dir="ltr" style="text-align: left;" trbidi="on">
Enums are always been the contract between the API (service) and its client(s). But if at all it is required to enhance the enum (add a new value) from API side, it is almost impossible to inform about the change to all its client(s). At the end, if the client implementation is not backward compatible it fails to parse the API response.<br />
<br />
<b>Example – 1:</b><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKGUCnloXRy9rvc1FdJkLpGCoSW-EzbXfYQuvygaVnGKyuMDylGIFImTA04P7ZucekKG4736hcWuqMeQG9tjhTR-6f8o_cLG37_ZSgNzB_H76FmGNLhxLX78yJhrgfNzF09CRLBgevpUZY/s1600/11.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" data-original-height="448" data-original-width="1408" height="202" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKGUCnloXRy9rvc1FdJkLpGCoSW-EzbXfYQuvygaVnGKyuMDylGIFImTA04P7ZucekKG4736hcWuqMeQG9tjhTR-6f8o_cLG37_ZSgNzB_H76FmGNLhxLX78yJhrgfNzF09CRLBgevpUZY/s640/11.png" width="640" /></a><br />
<div class="separator" style="clear: both; text-align: left;">
Here when we try to parse API response with a new enum value it ends up with below exception.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBRSv4OhRY6iRQQV9mYz-oz-ktssnEdKg5cmg6xTO4cVCRev_rYGHH0pOSXy1bYQZV-oARkzAAer2VlGbc22AMwDXB7Rrb8febwky29Zlz4v-NBiGgWVSOwknrcbEyPGKN5wOYwPMcHeV8/s1600/12.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="190" data-original-width="1394" height="86" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBRSv4OhRY6iRQQV9mYz-oz-ktssnEdKg5cmg6xTO4cVCRev_rYGHH0pOSXy1bYQZV-oARkzAAer2VlGbc22AMwDXB7Rrb8febwky29Zlz4v-NBiGgWVSOwknrcbEyPGKN5wOYwPMcHeV8/s640/12.png" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<i><span style="color: red;">com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `Status` from String "INTERMEDIATE": value not one of declared Enum instance names: [START, END] at [Source: (String)"{"status": "INTERMEDIATE"}"; line: 1, column: 12] (through reference chain: Resp["status"])</span></i></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<a href="https://www.blogger.com/blogger.g?blogID=6253472251172770602" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"></a><a href="https://www.blogger.com/blogger.g?blogID=6253472251172770602" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"></a><b>We can avoid such situation by making our client code backward compatible by following few best practices:</b><br />
<b><br /></b>
<b>Method - I : By replacing the invalid value by some default enum constant</b><br />
Always define a default enum value like EMPTY or INVALID or DEFAULT or UNKNOWN or _ etc. based on the best suitable<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbAHxr_-kgj2Ip4Ho6Wnm76cPO1XREpS7sVfFkzKxqjGepvpbg5KQRjV0nQD1I-tpfhvOHwTf_a1U5Nw5lCuGFnNMN4-PeS8_9SEKMS113tPlfP0WppULIfWeufPmb4S-grk0EYds68hDC/s1600/13.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" data-original-height="566" data-original-width="1432" height="252" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbAHxr_-kgj2Ip4Ho6Wnm76cPO1XREpS7sVfFkzKxqjGepvpbg5KQRjV0nQD1I-tpfhvOHwTf_a1U5Nw5lCuGFnNMN4-PeS8_9SEKMS113tPlfP0WppULIfWeufPmb4S-grk0EYds68hDC/s640/13.png" width="640" /></a><br />
<b>Test Cases:</b><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj25phw8i3tWnfXDeMvcKKW_4FcE2DqSYlQxEyqKupNNDQHd1_Uark51BSer4w8VvBhHSEGbosJ2pLCdmLwHvT9a52ZdPeUCgBiCrCOviTCw1ZsbW8FhGIpOSdpFkVaUiFYQ2hyphenhyphenj-tDvjoh/s1600/14.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" data-original-height="480" data-original-width="1422" height="216" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj25phw8i3tWnfXDeMvcKKW_4FcE2DqSYlQxEyqKupNNDQHd1_Uark51BSer4w8VvBhHSEGbosJ2pLCdmLwHvT9a52ZdPeUCgBiCrCOviTCw1ZsbW8FhGIpOSdpFkVaUiFYQ2hyphenhyphenj-tDvjoh/s640/14.png" width="640" /></a><br />
<br />
<b>Method - II : By setting the below deserialization feature to ObjetMapper object</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrG-KquiQNJn9fr3UpwVdijmHH40MRki3B54Lo8mS14Mkk45XspAdfJPd-CBaBCsIe7VhyphenhypheniFmV4aYCw3TITynwbZFeGOap1iKoBqnepI9GsFiSj9nlWd9XtVzUCbideNdUsWVYPiB312D3/s1600/15.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="140" data-original-width="1432" height="62" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrG-KquiQNJn9fr3UpwVdijmHH40MRki3B54Lo8mS14Mkk45XspAdfJPd-CBaBCsIe7VhyphenhypheniFmV4aYCw3TITynwbZFeGOap1iKoBqnepI9GsFiSj9nlWd9XtVzUCbideNdUsWVYPiB312D3/s640/15.png" width="640" /></a></div>
<b>Test Case:</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe7o0qlWYCs48snWdDpisfj8f31QdqEIW6ZvHvyowm-brxkkxA8CGOCireN7Gc5f_uCy7BkG1Z_xvzMTGmfddUv5Stv3MXMub39sgi24Pm4kGTUSyXLYOCkZrZ3YvkrBTqrVtt4UlSk9k-/s1600/16.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="386" data-original-width="1424" height="172" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe7o0qlWYCs48snWdDpisfj8f31QdqEIW6ZvHvyowm-brxkkxA8CGOCireN7Gc5f_uCy7BkG1Z_xvzMTGmfddUv5Stv3MXMub39sgi24Pm4kGTUSyXLYOCkZrZ3YvkrBTqrVtt4UlSk9k-/s640/16.png" width="640" /></a></div>
<br />
<b>Pros N Cons of the above two methods</b><br />
<br />
<ul style="text-align: left;">
<li>Method - I gives you a default enum constant which is NULL safe and you can easily ignore this through out your code.</li>
<li>Method - II gives you a NULL which prone to NullPointerException</li>
</ul>
<br />
<b><br /></b>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-34614958639824957502019-07-16T08:49:00.000-07:002019-07-16T09:17:25.508-07:00Toggleable Enum in Java<div dir="ltr" style="text-align: left;">I came across this below code in my code base where we just want to toggle the enum value. If it is DEBIT return CREDIT, if CREDIT return DEBIT like below.<br /><hr />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: navy; font-weight: bold;">enum </span>DebitCreditCode <span style="color: navy; font-weight: bold;">implements </span>Toggleable<DebitCreditCode> {
<span style="color: #660e7a; font-style: italic; font-weight: bold;">DEBIT</span>,
<span style="color: #660e7a; font-style: italic; font-weight: bold;">CREDIT<br /></span>} </pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: navy; font-weight: bold;">public static </span>DebitCreditCode getReverseOfPaymentDebitCreditCode(DebitCreditCode
debitOrCreditFromSummary) {
<span style="color: navy; font-weight: bold;">if </span>(debitOrCreditFromSummary != <span style="color: navy; font-weight: bold;">null </span>&& debitOrCreditFromSummary
.equals(DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">CREDIT</span>)) {
<span style="color: navy; font-weight: bold;">return </span>DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">DEBIT</span>;
} <span style="color: navy; font-weight: bold;">else if </span>(debitOrCreditFromSummary != <span style="color: navy; font-weight: bold;">null </span>&& debitOrCreditFromSummary
.equals(DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">DEBIT</span>)) {
<span style="color: navy; font-weight: bold;">return </span>DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">CREDIT</span>;
}
<span style="color: navy; font-weight: bold;">return null</span>;
}</pre>
<hr />This method is excellent and works as expected.</div>
<div dir="ltr" style="text-align: left;"> </div>
<div dir="ltr" style="text-align: left;"><strong>But…</strong><br /> If we want such requirement for any other enum,<br />
<ul>
<li>we have to define similar utility method for each <strong>enum</strong> and it is a repetitive job</li>
<li>we will be landed up with duplicate code</li>
</ul>
So, to get rid of this, I have designed the below solution through which we can achieve the same without writing new method every time.</div>
<div dir="ltr" style="text-align: left;"><br /> <strong><u>Step – 1</u> : </strong><em>Define this below interface in your common module. This is a one time job.</em><br /><hr />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: navy; font-weight: bold;">interface </span>Toggleable<<span style="color: #20999d;">T </span><span style="color: navy; font-weight: bold;">extends </span>Enum<<span style="color: #20999d;">T</span>>> {
<span style="color: navy; font-weight: bold;">default </span><span style="color: #20999d;">T </span>toggle() {
<span style="color: navy; font-weight: bold;">final </span><span style="color: #20999d;">T</span>[] enumConstants = (<span style="color: #20999d;">T</span>[]) <span style="color: navy; font-weight: bold;">this</span>.getClass().getEnumConstants();
<span style="color: navy; font-weight: bold;">if </span>(enumConstants == <span style="color: navy; font-weight: bold;">null</span>) {
<span style="color: navy; font-weight: bold;">throw new </span>UnsupportedOperationException(<span style="color: green; font-weight: bold;">"Only enum can support toggling"</span>);
}
<span style="color: navy; font-weight: bold;">if </span>(enumConstants.<span style="color: #660e7a; font-weight: bold;">length </span>!= <span style="color: blue;">2</span>) {
<span style="color: navy; font-weight: bold;">throw new </span>UnsupportedOperationException(<span style="color: green; font-weight: bold;">"Enum must have 2 objects to support toggling"</span>);
}
<span style="color: navy; font-weight: bold;">return </span>enumConstants[<span style="color: blue;">0</span>] == <span style="color: navy; font-weight: bold;">this </span>? enumConstants[<span style="color: blue;">1</span>] : enumConstants[<span style="color: blue;">0</span>];
}
}</pre>
<hr />
<pre spellcheck="false"><strong><u>Step – 2</u> : </strong><em>Just implement the above interface to your </em><strong><em>enum</em></strong><em> class where you want this
toggle/reverse feature like below :</em></pre>
<hr />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: navy; font-weight: bold;">enum </span>DebitCreditCode <span style="color: navy; font-weight: bold;">implements </span>Toggleable<DebitCreditCode> {
<span style="color: #660e7a; font-style: italic; font-weight: bold;">DEBIT</span>,
<span style="color: #660e7a; font-style: italic; font-weight: bold;">CREDIT<br /></span>}</pre>
<hr />
<pre spellcheck="false"><strong><u>Step – 3</u> : </strong><em>Call method </em><strong><em>toggle()</em></strong><em> on the </em><strong><em>enum</em></strong><em> object like</em></pre>
<hr />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: navy; font-weight: bold;">final </span>DebitCreditCode toggled = DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">DEBIT</span>.toggle();
Assert.<span style="font-style: italic;">assertEquals</span>(DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">CREDIT</span>, toggled);
<span style="color: navy; font-weight: bold;">final </span>DebitCreditCode original = toggled.toggle();
Assert.<span style="font-style: italic;">assertEquals</span>(DebitCreditCode.<span style="color: #660e7a; font-style: italic; font-weight: bold;">DEBIT</span>, original);</pre>
<hr />
<pre spellcheck="false">Find complete code <a href="https://github.com/PrabhatKJena/Developer-Utility/blob/master/src/test/java/edu/pk/dev/java/util/ToggleableTest.java">here</a> </pre>
</div>Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-55649009400839104742018-09-07T04:40:00.001-07:002018-09-07T04:40:35.032-07:00Your Java method should warn about NPE while coding itself<div dir="ltr" style="text-align: left;" trbidi="on">
Define your method is such way that, any IDE or Static Code Analyzer can sense the <i><b><a href="https://www.quora.com/Why-was-the-Null-Pointer-Exception-in-Java-called-a-billion-dollar-mistake" target="_blank"><span style="color: red;">billion-dollar mistake</span></a></b></i>, aka <b><span style="color: red;">NullPointerException</span></b> while writing the code to call the method.<br />
<br />
<div class="MsoNormal" style="caret-color: rgb(0, 0, 0); font-family: Calibri, sans-serif; font-size: 12pt; margin: 0in 0in 0.0001pt; text-size-adjust: auto;">
<b><span style="font-size: 11pt;">Here are some best practices while defining a new Java method.</span></b><span style="font-size: 11pt;"> </span></div>
<div class="MsoListParagraph" style="caret-color: rgb(0, 0, 0); font-family: Calibri, sans-serif; font-size: 12pt; margin: 0in 0in 0.0001pt 0.5in; text-size-adjust: auto;">
<o:p></o:p></div>
<ul style="text-align: left;">
<li>Method should have clear documentation with</li>
<ul>
<li class="MsoListParagraph" style="font-size: 12pt; margin: 0in 0in 0.0001pt;"><span style="font-size: 11pt;">Purpose of the method</span></li>
<li class="MsoListParagraph" style="font-size: 12pt; margin: 0in 0in 0.0001pt;"><span style="font-size: 11pt;">Parameters of the method – Mark the parameter with<span class="Apple-converted-space"> </span></span><span style="background-color: yellow; color: olive; font-family: "menlo"; font-size: 9pt;">@javax.annotation.Nonnull</span><span style="color: olive; font-family: "menlo"; font-size: 9pt;"> </span><span style="font-size: 11pt;">if null is not expected</span></li>
<li class="MsoListParagraph" style="font-size: 12pt; margin: 0in 0in 0.0001pt;"><span style="font-size: 11pt;">Return type of the method – Mark the return type with<span class="Apple-converted-space"> </span></span><span style="background-color: yellow; color: olive; font-family: "menlo"; font-size: 9pt;">@javax.annotation.Nullable</span><span style="font-size: 11pt;"><span class="Apple-converted-space"> </span>if it can be null</span></li>
</ul>
</ul>
<ul style="text-align: left;">
</ul>
Example:<br />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">/**</span><span style="color: grey; font-style: italic;"> </span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">* This method filters product from the productList by supplied productId and type and return the same. </span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">* If no match found then returns null.</span><span style="color: grey; font-style: italic;"> </span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">*</span><span style="color: grey; font-style: italic;"> </span><span style="color: grey; font-style: italic; font-weight: bold;">@param </span><span style="color: #3d3d3d; font-style: italic; font-weight: bold;">productId</span><span style="color: #3d3d3d; font-style: italic; font-weight: bold;"> </span><i><span style="color: #3d3d3d;">a non-null product I</span><span style="color: #3d3d3d;">D</span><span style="color: #3d3d3d; font-weight: bold;"> </span>for which the filter is requested</i></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">* </span><span style="color: grey; font-style: italic; font-weight: bold;">@param </span><span style="color: #3d3d3d; font-style: italic; font-weight: bold;">type</span><span style="color: #3d3d3d; font-style: italic; font-weight: bold;"> </span><i><span style="color: #3d3d3d;">a non-null type value </span>for which the filter is requested</i></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">* </span><span style="color: grey; font-style: italic; font-weight: bold;">@return </span><span style="color: grey; font-style: italic;">Product if found the match by productId and type else return null</span><span style="color: grey; font-style: italic;"> </span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;">*/</span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: navy; font-weight: bold;">public </span><span style="color: olive;">@Nullable </span>Product filterProductByIdAndType(<span style="color: olive;">@Nonnull </span>BigInteger productId, <span style="color: olive;">@Nonnull </span>Character type) {
Product product = <span style="color: navy; font-weight: bold;">null</span>;
<span style="color: navy; font-weight: bold;">for </span>(Product eachProduct : <span style="color: #660e7a; font-weight: bold;">productList</span>) {
<span style="color: navy; font-weight: bold;">if </span>(productId.equals(eachProduct.getId()) && type.equals(eachProduct.getType())) {
product = eachProduct;
<span style="color: navy; font-weight: bold;">break</span>;
}
}
<span style="color: navy; font-weight: bold;">return </span>product;
}</pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;">
</pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"></pre>
<pre style="background-color: white;"><div class="MsoNormal" style="caret-color: rgb(0, 0, 0); font-family: Calibri, sans-serif; font-size: 12pt; margin: 0in 0in 0.0001pt; text-size-adjust: auto; white-space: normal;">
<b><span style="font-size: 11pt;">How it helps while calling the method?</span></b></div>
<ol start="1" style="caret-color: rgb(0, 0, 0); font-family: -webkit-standard; font-size: 9pt; margin-bottom: 0in; margin-top: 0in; text-size-adjust: auto; white-space: normal;" type="1">
<li class="MsoListParagraph" style="font-family: Calibri, sans-serif; font-size: 12pt; margin: 0in 0in 0.0001pt;"><span style="font-size: 11pt;">It warns that the argument might be null while the method is expecting a<span class="Apple-converted-space"> </span><b>Nonnull</b><span class="Apple-converted-space"> </span>parameter. In this case<span class="Apple-converted-space"> </span><b><i>productId</i></b><span class="Apple-converted-space"> </span>may be null because the assignment is conditional.</span></li>
</ol>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZLEjbjwZ2jfvcP55hUVllJBAX4fDLTmtKGNmW_VOKJMp2k6WMsJm4ZxaN3MRsSMxp9gXXaMX5bil5c7zgEEckTRBPe6GdHFXmSGqHJ4Ml-fb3rOvNX6mI1UN56Jt4PJCkoxCxo6hmQsBw/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="230" data-original-width="1346" height="108" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZLEjbjwZ2jfvcP55hUVllJBAX4fDLTmtKGNmW_VOKJMp2k6WMsJm4ZxaN3MRsSMxp9gXXaMX5bil5c7zgEEckTRBPe6GdHFXmSGqHJ4Ml-fb3rOvNX6mI1UN56Jt4PJCkoxCxo6hmQsBw/s640/1.png" width="640" /></a></div>
<ol start="2" style="caret-color: rgb(0, 0, 0); font-family: -webkit-standard; margin-bottom: 0in; margin-top: 0in; text-size-adjust: auto; white-space: normal;" type="1">
<li class="MsoListParagraph" style="font-family: Calibri, sans-serif; font-size: 12pt; margin: 0in 0in 0.0001pt;"><span style="font-size: 11pt;">It also warns about the NPE because there is a possibility of getting<span class="Apple-converted-space"> </span><b>Null</b><span class="Apple-converted-space"> </span>from the method. In this case the method can return<span class="Apple-converted-space"> </span><b>null<span class="Apple-converted-space"> </span></b>as per the method documentation.</span></li>
</ol>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDCR3zflolbDDE0ki090kUYZzBMxTabX4PZUVbT8gF3pXL6ql0T_uWvZgDqC7VV-PqqdCOqz2MUzbgjKNh7VIYQDHXyAJoB8xOawCvSEm8A6-GLzr5rrBLRlXObfWEJhXAoV5xm6k9bHjk/s1600/3.png" imageanchor="1" style="font-family: Times; margin-left: 1em; margin-right: 1em; text-align: center; white-space: normal;"><img border="0" data-original-height="236" data-original-width="1348" height="112" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDCR3zflolbDDE0ki090kUYZzBMxTabX4PZUVbT8gF3pXL6ql0T_uWvZgDqC7VV-PqqdCOqz2MUzbgjKNh7VIYQDHXyAJoB8xOawCvSEm8A6-GLzr5rrBLRlXObfWEJhXAoV5xm6k9bHjk/s640/3.png" width="640" /></a></div>
</pre>
<div class="separator" style="clear: both; text-align: left;">
<span style="caret-color: rgb(0, 0, 0); font-size: 14.6667px; text-size-adjust: auto;"><i><span style="color: blue; font-family: Georgia, Times New Roman, serif;">Let’s follow these best practices to avoid nightmares.<span class="Apple-converted-space"> </span></span></i></span></div>
<pre style="background-color: white;"><span style="font-family: "calibri" , sans-serif;"><span style="font-size: 14.6667px; white-space: normal;">
</span></span></pre>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-5386621520459790472017-02-16T03:26:00.003-08:002018-01-30T05:42:31.688-08:00Do You Really Understand java.lang.String.split(regex) Method ?<div dir="ltr" style="text-align: left;" trbidi="on">
You are in surprise that why this post is here under "secretsinjava.blogspot.com"? What is the secret here? But believe me, the secret I am going to explore here is hardly known by someone.<br />
<br />
We all know that <i><b>String.split("regex")</b></i> gives an array of string separated by the supplied "regex". Now answer for the below statement:<br />
<i>"Alpha:Beta:Gama".split(":"); </i><br />
It is very simple and the value returned by split method is <i>{"Alpha", "Beta", "Gama"}.</i><br />
<br />
Now what about <i><b>"Alpha:".split(":"), "Beta::".split(":") and "Alpha::Gama".split(":")</b> </i>?<br />
If you are thinking the answers will be like {"Alpha", ""} , {"Beta", "", ""} and {"Alpha":"":"Gama"} then you are absolutely wrong and you should know the secret of this.<br />
<br />
Before going to the secret, I will tell the answers so that you will decide whether it is worth knowing or not. The answers will be like {"Alpha"}, {"Beta"} and {"Alpha","","Gama"}.<br />
<br />
When we call the <i>String.split("regex") </i>method, this internally calls the below overloaded method with extra argument "limit" set to 0.<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgR8dOkTT0mhyZxeKlRX61O42CpH54EQ26WidGwxVOysIaUCB6kuwC7Rl5COSWzJB54dn9OO8yYt0p21D987qfyoF2hKZFVahBVWR6PN0ULh3Ofs1GupLQV-nEXOmCo1BYeaUfvM8qBEQ6W/s1600/Screenshot_5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgR8dOkTT0mhyZxeKlRX61O42CpH54EQ26WidGwxVOysIaUCB6kuwC7Rl5COSWzJB54dn9OO8yYt0p21D987qfyoF2hKZFVahBVWR6PN0ULh3Ofs1GupLQV-nEXOmCo1BYeaUfvM8qBEQ6W/s1600/Screenshot_5.png" /></a></div>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"></pre>
Here is the source code for reference :<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_H9tJSapy71meXuuKlTgNh904VsufMkYK9LxOl6euMe81tkYfSGi2acxHphbbzkzErQopyxxEWA9n7uizLOXt2PAIAyp7fWM9soczybGNrtRa5sRpS2h_KYSkJz-K09fUC8YvXy3F4ARS/s1600/Screenshot_4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_H9tJSapy71meXuuKlTgNh904VsufMkYK9LxOl6euMe81tkYfSGi2acxHphbbzkzErQopyxxEWA9n7uizLOXt2PAIAyp7fWM9soczybGNrtRa5sRpS2h_KYSkJz-K09fUC8YvXy3F4ARS/s1600/Screenshot_4.png" /></a></div>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"></pre>
<pre style="background-color: white;"></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;">Here the secret is all about he <i style="font-weight: bold;">limit </i>parameter. As per the Java API specification, </span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;"><i><b>The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.</b> i.e</i></span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;"><i>when <b>limit > 0</b> <b>:</b> the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter</i></span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;"><i>when <b>limit == 0</b> <b>:</b> the pattern will be applied as many times as possible and the array can have any length, </i></span></span><i style="font-family: times; white-space: normal;">and trailing empty strings will be discarded</i></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;"><i>when <b>limit < 0 : </b>then the pattern will be applied as many times as possible, the array can have any length</i></span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;"><i>
</i></span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;">Now let's see some examples:</span></span></pre>
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyQGUbsXYW_ikLHJPTJ6-GEVrVFgFyWdESrQZ0ktncneou1r1zzgDVv4yg4y8307xqRsdg1OWIKzyiTbx5MOj3u47VsvgZysmsieKedTqCxFHLAqBYVMqCU9ePuUTX1fNhKc1SvXFMhP5C/s1600/Screenshot_2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyQGUbsXYW_ikLHJPTJ6-GEVrVFgFyWdESrQZ0ktncneou1r1zzgDVv4yg4y8307xqRsdg1OWIKzyiTbx5MOj3u47VsvgZysmsieKedTqCxFHLAqBYVMqCU9ePuUTX1fNhKc1SvXFMhP5C/s1600/Screenshot_2.png" /></a></div>
<b>Output :</b><br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWAml6EWa7WoY-KDt7DRyFCbZDq8Z6hD41lPMr70JKkpEMGA31VGkkCZfQd2FxlI-3NihWJRphrtV3zXm-3v3ojQjVyH0TAtJlpGbmLH-AdHDsmjEIFGCgk0tseo_ziVralbPkwIxhOiNb/s1600/Screenshot_3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWAml6EWa7WoY-KDt7DRyFCbZDq8Z6hD41lPMr70JKkpEMGA31VGkkCZfQd2FxlI-3NihWJRphrtV3zXm-3v3ojQjVyH0TAtJlpGbmLH-AdHDsmjEIFGCgk0tseo_ziVralbPkwIxhOiNb/s1600/Screenshot_3.png" /></a></div>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;">
</span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;">I hope it is clear about the secret in <b>String.split("regex") </b>method. Please feel free to ask/provide your doubt/comments. </span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;">
</span></span></pre>
<pre style="background-color: white;"><span style="font-family: "times";"><span style="white-space: normal;"> </span><span style="white-space: normal;"><script src="https://github.paypal.com/gist/prajena/3f633b24cbc9699830344e09c51a6e6a.js"></script></span></span></pre>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-83203918513336053912016-12-26T01:45:00.000-08:002016-12-26T01:48:51.535-08:00Unknown facts about Date Format Validation in Java<div dir="ltr" style="text-align: left;" trbidi="on">
Have you ever think of validating a date given in string form whether it's a valid date or not?<br />
e.g. :<br />
30-11-2016(dd-MM-yyyy) --> Valid date<br />
31-11-2016(dd-MM-yyyy) --> Invalid date, since November has only 30 days<br />
<br />
Now you think what is there, it's pretty simple. Now you can think of using any 3rd party utility library (like apache-common-util) to validate this.<br />
<br />
But the point here is, how these utility libraries do this validation ? Now the <i><b>java.text.SimpleDateFormat</b></i> class in java core API comes to our mind.<br />
<br />
Let's see an example how can we validate using this class :<br />
<u>Example - 1</u><br />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;">SimpleDateFormat format = <span style="color: navy; font-weight: bold;">new </span>SimpleDateFormat(<span style="color: green; font-weight: bold;">"dd-MMM-yyyy"</span>);
Date date = format.parse(<span style="color: green; font-weight: bold;">"31-JAN-2016"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(date);
<span style="color: grey; font-style: italic;">/*</span><span style="color: grey; font-style: italic;">O/P</span><span style="color: grey; font-style: italic;">---</span><span style="color: grey; font-style: italic;">Sun Jan 31 00:00:00 IST 2016</span><span style="color: grey; font-style: italic;"> */</span></pre>
<br />
<u>Example - 2</u><br />
<u><br /></u>
<br />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;">SimpleDateFormat format = <span style="color: navy; font-weight: bold;">new </span>SimpleDateFormat(<span style="color: green; font-weight: bold;">"dd-MMM-yyyy"</span>);
Date date = format.parse(<span style="color: green; font-weight: bold;">"31-JEN-2016"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(date);
<span style="color: grey; font-style: italic;">/*</span><span style="color: grey; font-style: italic;">O/P</span><span style="color: grey; font-style: italic;">---</span><span style="color: grey; font-style: italic;">Exception in thread "main" java.text.ParseException: Unparseable date: "31-JEN-2016"</span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"> <span style="color: #999999;">at java.text.DateFormat.parse(DateFormat.java:366)</span></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"><span style="color: grey; font-style: italic;"> at Solution.main(Solution.java:21)</span><span style="color: grey; font-style: italic;"> ...</span><span style="color: grey; font-style: italic;">
</span><span style="color: grey; font-style: italic;"> */</span></pre>
<br />
Here we can see the validation is pretty simple and straight forward. But let's see some other use cases and will decide whether the validation is really such straight forward ?<br />
<br />
<u>Example - 3</u><br />
<br />
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;">SimpleDateFormat format = <span style="color: navy; font-weight: bold;">new </span>SimpleDateFormat(<span style="color: green; font-weight: bold;">"dd-MMM-yyyy"</span>);
Date date = format.parse(<span style="color: green; font-weight: bold;">"32-JAN-2016"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(date);
<span style="color: grey; font-style: italic;">/*</span><span style="color: grey; font-style: italic;">O/P</span><span style="color: grey; font-style: italic;">---</span><span style="color: grey; font-style: italic;"> Mon Feb 01 00:00:00 IST 2016</span><span style="color: grey; font-style: italic;"> */</span></pre>
<br />
Here you see even the input string is an invalid date but the formatter can parse it and returning the next valid date by incrementing the day. (from 32-JAN to 01-FEB).<br />
Now you are confused that, "how can we validate in a correct way ?".<br />
<br />
Here is the secret of SimpleDateFormat:<br />
<br />
<b><i>SimpleDateFormat </i></b>extends <i style="font-weight: bold;">java.text.DateFormat </i>which having this below method<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKZam8h_SP-OGVYm6At9aEu4HhoE7EwYPHDfC7UOVNg7m7BWcrR_sEMXsG1U8P9XzditffQd3XXvd3uyJrHeLSWxZz8xt5TkuveybtkwbRF0PAbCsDulcXt7ZFClYZVMK8HWtJxc78SWH5/s1600/sc2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="370" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKZam8h_SP-OGVYm6At9aEu4HhoE7EwYPHDfC7UOVNg7m7BWcrR_sEMXsG1U8P9XzditffQd3XXvd3uyJrHeLSWxZz8xt5TkuveybtkwbRF0PAbCsDulcXt7ZFClYZVMK8HWtJxc78SWH5/s640/sc2.png" width="640" /></a></div>
<pre><span style="font-family: "times" , "times new roman" , serif;">This above method uses the heuristics to interpret the given input. So make sure to disable </span></pre>
<pre><span style="font-family: "times" , "times new roman" , serif;">this property<span style="font-size: 12px;"> </span></span><span style="font-family: "times" , "times new roman" , serif;">by setting as </span><b style="font-family: Times, "Times New Roman", serif;"><i>formater.setLenient(false);</i></b></pre>
<pre><span style="font-family: "times" , "times new roman" , serif;"><b><i>
</i></b></span></pre>
<pre><span style="font-family: "times" , "times new roman" , serif;"><u>Example - 3 modified</u></span></pre>
<pre><span style="font-family: "times" , "times new roman" , serif;"><u>
</u></span></pre>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTRquJfoskB6xxtI_O05EJsKR52k1Xvvgm5TyeisI5oIFcZdCSiExAvjux4OcgUpXNoC0QiGYl-3DulcqylLEOYWmQBxCi9ooR0J1I7QuECQ3LCUtLKb3GxGV4pRY7jwH7-3_2p4BzAFlG/s1600/sc3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="206" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTRquJfoskB6xxtI_O05EJsKR52k1Xvvgm5TyeisI5oIFcZdCSiExAvjux4OcgUpXNoC0QiGYl-3DulcqylLEOYWmQBxCi9ooR0J1I7QuECQ3LCUtLKb3GxGV4pRY7jwH7-3_2p4BzAFlG/s640/sc3.png" width="640" /></a></div>
<pre></pre>
<pre><span style="font-family: "times" , "times new roman" , serif;"><u>
</u></span></pre>
<pre><span style="font-family: "times" , "times new roman" , serif;">Now it validated properly as we want.</span></pre>
<pre style="font-family: Menlo; font-size: 9pt;"></pre>
<pre style="background-color: white; font-family: Menlo; font-size: 9pt;"></pre>
<br />
<br />
<br />
<br /></div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-25094429371396475702016-08-20T21:22:00.001-07:002016-08-20T21:22:28.659-07:00Detect Deadlock Programmatically in Your Applicaion<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
What is a Deadlock ?</h3>
<div style="text-align: left;">
It is a condition where two or more threads are blocked forever because they are waiting for each other to get the lock/resource. And it happens because of the inappropriate use of mutual exclusion locks.</div>
<div style="text-align: left;">
So let's see a sample of code where a deadlock situation is created intensionally for demonstrate purpose. </div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgg1SWWdWI_09Zaw_PWMERGhm9daXx7ygoj24Kf892q9b6XYSfgsS2FLcAzxJcwMT2RyiOTjODvA05peRzb8NHlK124HbRGx3n5TXTaSBLMmCyazC2mgvEm3MOYtA3LAAPvwRdHIBKBRA0z/s1600/Selection_004.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgg1SWWdWI_09Zaw_PWMERGhm9daXx7ygoj24Kf892q9b6XYSfgsS2FLcAzxJcwMT2RyiOTjODvA05peRzb8NHlK124HbRGx3n5TXTaSBLMmCyazC2mgvEm3MOYtA3LAAPvwRdHIBKBRA0z/s1600/Selection_004.png" /></a></div>
<u><b>Output :</b></u><br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfmG_FVAuZJ3Sq7Ox929CihJapp4TBSUEXNBMvbkhkcu-5hl6Ssl0bOK_UWhVN0yr6R6cNBdGlB5Cj5A_ZLOAFjpvtVJ8o4Jmx04u5OY8i2bbOp63fN8VUsl_d-GS2E1q3gllRRksKEbnE/s1600/Selection_006.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfmG_FVAuZJ3Sq7Ox929CihJapp4TBSUEXNBMvbkhkcu-5hl6Ssl0bOK_UWhVN0yr6R6cNBdGlB5Cj5A_ZLOAFjpvtVJ8o4Jmx04u5OY8i2bbOp63fN8VUsl_d-GS2E1q3gllRRksKEbnE/s400/Selection_006.png" /></a><br />
Here you can observe both th threads are waiting for each other to get the lock.<br />
<br />
<h3 style="text-align: left;">
How to detect deadlock threads in your application?</h3>
<div style="text-align: left;">
Well, so Java has given default tools with the JDK package; using those we can detect the thread dumps which are in deadlock state. And also there are so many 3rd party tools available in market you can use for the same. </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Here we will discuss about Java's default tool and how programmatically we can detect deadlock.</div>
<h3 style="text-align: left;">
Detect deadlock programmatically :</h3>
<div style="text-align: left;">
OK, so let's create a daemon thread which runs in background and detects if there is any deadlock thread and prints.</div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiavQs6yTQWF6qLY8TPXXjXmtVPc_uCev7rTWG_VGFD7iKOT6A-GeNKcE2xU6o-Zq0dN6GCfBTkAbpp-_3o2rMc7Zjpde_LkhxKlA4yGAJYT1SWTRF_jyIAjs5J63kGfdJpsQid9sMHx9di/s1600/Selection_003.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiavQs6yTQWF6qLY8TPXXjXmtVPc_uCev7rTWG_VGFD7iKOT6A-GeNKcE2xU6o-Zq0dN6GCfBTkAbpp-_3o2rMc7Zjpde_LkhxKlA4yGAJYT1SWTRF_jyIAjs5J63kGfdJpsQid9sMHx9di/s1600/Selection_003.png" /></a></div>
<div style="text-align: left;">
This is a thread which runs in background as daemon thread till the JVM is alive and repeatedly detects deadlock in every 5 seconds. </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Java 5 introduced new classes under package <span style="color: blue;"><i>java.lang.management</i></span></div>
<div style="text-align: left;">
<i><b>ThreadMXBean </b>: The management interface for the thread system of the Java virtual machine.</i></div>
<div style="text-align: left;">
<i><b>ManagementFactory</b> : This is a factory class to get ThreadMXBean instance.</i></div>
<div style="text-align: left;">
<i><b>ThreadInfo</b> : This class contains basic thread info like thread ID and thread name.</i></div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Now let's add the detector thread to the main program :</div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9Xzn-HEDu-osD8F9yuHg9WB_5e-43G8CCa-C75zMGRLPdDQoLCUPiuta0k3faKCaE4pmQve_kYTC6sEuvfsSP1uYYVBqtDQnSeSAc2T9SnSMp2WgLqtJURUaC_NweUXY6kRTP7BhwvEPT/s1600/Selection_007.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9Xzn-HEDu-osD8F9yuHg9WB_5e-43G8CCa-C75zMGRLPdDQoLCUPiuta0k3faKCaE4pmQve_kYTC6sEuvfsSP1uYYVBqtDQnSeSAc2T9SnSMp2WgLqtJURUaC_NweUXY6kRTP7BhwvEPT/s1600/Selection_007.png" /></a></div>
<div style="text-align: left;">
<u><b>Output:</b></u></div>
<div style="text-align: left;">
<b><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid6n7-fcIClCiZKiWUflsFAhyqZE7Ox8lH71NEDjiIgGNsMHiSTn6IZoRnTuKcDmM4qg4sEoKPE4LMmS5JCJggVegJ34oAzm2FWF2bXemiePU3lBAoARS-ocXcFGG34S4qMk7wuotNzZCz/s1600/Selection_008.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid6n7-fcIClCiZKiWUflsFAhyqZE7Ox8lH71NEDjiIgGNsMHiSTn6IZoRnTuKcDmM4qg4sEoKPE4LMmS5JCJggVegJ34oAzm2FWF2bXemiePU3lBAoARS-ocXcFGG34S4qMk7wuotNzZCz/s1600/Selection_008.png" /></a> </b></div>
<h3 style="text-align: left;">
<b> </b></h3>
<h3 style="text-align: left;">
<b>Detect deadlock using Java's default tools :</b></h3>
<div style="text-align: left;">
<b>Using jconsole :</b></div>
<div style="text-align: left;">
Java has provided jconsole tool in .../<jdk_home_dir>/bin<b></b></div>
<div style="text-align: left;">
Step - 1: ../bin/$ jconsole</div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4Aj3s-Q7zskDCRcnIV9NK5R1QWwji7TaHGoIXoyVdYj2YHF784Vqv5yZ6-ynKieHKS5qVBiASpNVm9x0jmJOT0BO58mfpfP5gbH_I_TmEV-JR5q8xqmIju7T9xCarNCSv3JXK4NFthKuZ/s1600/Selection_009.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4Aj3s-Q7zskDCRcnIV9NK5R1QWwji7TaHGoIXoyVdYj2YHF784Vqv5yZ6-ynKieHKS5qVBiASpNVm9x0jmJOT0BO58mfpfP5gbH_I_TmEV-JR5q8xqmIju7T9xCarNCSv3JXK4NFthKuZ/s1600/Selection_009.png" /></a></div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
</div>
<div style="text-align: left;">
Step 2 : Select process name with PID and click <b>Connect</b></div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1peH_kDQRuC3LjjdLMoGY5mNGltm2kQgh-oU0fmGnIoOvgpprxgBzDzxPFAzJmKmNpEWtXmdnCDHg2H4dnpJ4d6814uAu_SUFyLPEL1ILLQZDhLcB7gAVRnHD4ZIt2ojtOxjDiSTYSIWs/s1600/Selection_011.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1peH_kDQRuC3LjjdLMoGY5mNGltm2kQgh-oU0fmGnIoOvgpprxgBzDzxPFAzJmKmNpEWtXmdnCDHg2H4dnpJ4d6814uAu_SUFyLPEL1ILLQZDhLcB7gAVRnHD4ZIt2ojtOxjDiSTYSIWs/s1600/Selection_011.png" /></a></div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Step - 3 : Select <b>Thread</b> tab and click <b>Detect Deadlock</b></div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZazhA3wwXkEX2DMbXqZrquHnVFfyxqTfr1D2iHn9ou5YSCSIs4_KHXvxVft7FXF-D7Wq3ibxbsGbZzPz-ux8nlYwHMd_E-3gdHm_dQwuw8FzmpL7CqcNBvAx7OtMxP3I2-ucLvnHLx9y0/s1600/Selection_012.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZazhA3wwXkEX2DMbXqZrquHnVFfyxqTfr1D2iHn9ou5YSCSIs4_KHXvxVft7FXF-D7Wq3ibxbsGbZzPz-ux8nlYwHMd_E-3gdHm_dQwuw8FzmpL7CqcNBvAx7OtMxP3I2-ucLvnHLx9y0/s1600/Selection_012.png" /></a></div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Final output window:</div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvssfYYi__gIkjF7eh5k6LW0J5pG0RDLb14o40w4hmwmLb-tDiXIKxFInP8E_bTCEF9_Ps5Ieo-ZnLfNXbjsnJnyhAAEGwLUhCkyWRfVxlSE63KCMA0FvbndC0TFWPoEm0otSXrXBTGT6S/s1600/Selection_013.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvssfYYi__gIkjF7eh5k6LW0J5pG0RDLb14o40w4hmwmLb-tDiXIKxFInP8E_bTCEF9_Ps5Ieo-ZnLfNXbjsnJnyhAAEGwLUhCkyWRfVxlSE63KCMA0FvbndC0TFWPoEm0otSXrXBTGT6S/s1600/Selection_013.png" /></a> </div>
<h3 style="text-align: left;">
Using jstack :</h3>
<div style="text-align: left;">
Java has provided jstack tool in .../<jdk_home_dir>/bin</div>
<div style="text-align: left;">
Step - 1: ../bin/$ jstack <PID></div>
<div style="text-align: left;">
Ex : ../bin/$ jstack 17472 </div>
<div style="text-align: left;">
<u><b>Output:</b></u></div>
<div style="text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPkdRrXElg9BKLp3kwI54O_7wBmiZciNIkmSBJFbBLVG9PzJKt_AwPqmCpvav7f2TZwD6_mSKRZAnGFzY9O1-PDV0tCNiHRCixX-yyn9iOMafpM5VzflhDb-g9DXWCgjLq7k2-AdrFXl6F/s1600/Selection_014.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPkdRrXElg9BKLp3kwI54O_7wBmiZciNIkmSBJFbBLVG9PzJKt_AwPqmCpvav7f2TZwD6_mSKRZAnGFzY9O1-PDV0tCNiHRCixX-yyn9iOMafpM5VzflhDb-g9DXWCgjLq7k2-AdrFXl6F/s1600/Selection_014.png" /></a></div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
That's all for this post.
<span style="color: blue;"><span style="color: black;">Please feel free to give your comment/suggestion. Thank you.</span> </span></div>
<div style="text-align: left;">
</div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-69302288508524531902016-08-17T09:53:00.002-07:002016-08-17T09:53:45.259-07:00Why enum is the best approach to implement a Singleton class ?<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous blog (<a href="http://secretsinjava.blogspot.in/2016/08/implement-singleton-class-in-efficient.html" target="_blank">Implement SIngleton class in an efficient way</a>), we have already discussed about all the approaches to implement a singleton class and concluded with the enum type implementation. As mentioned earlier enum is completely safe from reflection and serialization attack.<br />
<br />
Now we will see in details that,<br />
- Is enum really safe<br />
- Whether we can break an enum from singleton with either reflection or serialization.<br />
<br />
Before proceeding to this let's know more about enum in depth.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwtChxtw7_OilqZEgd6u0prtPPtpYIMgRGU2qasDzgQtlSbGeKWtmzv5pPH6sjMcKmAyx1LjksksY9rIBTaecXHr3XTR-kYTfnuBMu6VH8ksw4MTLpf04kSjVuy8IsMey0XgzaDLMU3twC/s1600/Selection_029.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwtChxtw7_OilqZEgd6u0prtPPtpYIMgRGU2qasDzgQtlSbGeKWtmzv5pPH6sjMcKmAyx1LjksksY9rIBTaecXHr3XTR-kYTfnuBMu6VH8ksw4MTLpf04kSjVuy8IsMey0XgzaDLMU3twC/s1600/Selection_029.png" /></a><br />
OK, what you think about this simple enum ? What is exactly an enum ? <br />
<br />
Well, an enum is a simple class which extends <i><b>java.lang.Enum</b></i> class. Believe me this is the truth behind <b>enum</b> keyword. Java compiler plays the main role here while compiling the enum; it converts the enum to a normal class and extends that class directly from<b> Enum</b> class rather than <b>Object</b> class. Now let's check the truth.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoznCx60DhGMA6zzcQkDy9mOdCwJMoZjgXu8BjaOIosBozYzVddy8W04LPQpxQs8dSgWc9FSE60uK849zDvA5VSDyMoprBCXHgtHDtb9AV_Z-73fLilsvCiUDcgARP1_odPZZPjaDmhjQ6/s1600/Selection_018.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoznCx60DhGMA6zzcQkDy9mOdCwJMoZjgXu8BjaOIosBozYzVddy8W04LPQpxQs8dSgWc9FSE60uK849zDvA5VSDyMoprBCXHgtHDtb9AV_Z-73fLilsvCiUDcgARP1_odPZZPjaDmhjQ6/s1600/Selection_018.png" /></a><br />
So, the compiler injects 3 more elements (2 methods and 1 static block).<br />
<br />
Let's try to instantiate an enum using java Reflection API.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjff3m_bdebWsgI8n2TMDmk6qMnIVsaNvDEQfine4gz7gm4tFsjP1cdXHmgYCQu7E5sZoKChLUWiAZJouTRlHmMU0EtzSQIdAWzJHlambs2QW7kfPw0vTGphuC94MgSucQIG0I88bjdsrCA/s1600/Selection_026.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjff3m_bdebWsgI8n2TMDmk6qMnIVsaNvDEQfine4gz7gm4tFsjP1cdXHmgYCQu7E5sZoKChLUWiAZJouTRlHmMU0EtzSQIdAWzJHlambs2QW7kfPw0vTGphuC94MgSucQIG0I88bjdsrCA/s1600/Selection_026.png" /></a><br />
<u>Test class</u><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSG31kshJjF2WEq277ofIBpEIDhS_GIHDwMcNJr1K3ZHegWpAmVLYqyU9EgKQbhRgdP9cdBqj3DGh0KmwbF5vLpKpkazAdCfFgnccpYP3H5WWkg7LQbN40xTMG_d3UeR4sePjT8k7tRD6j/s1600/Selection_020.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSG31kshJjF2WEq277ofIBpEIDhS_GIHDwMcNJr1K3ZHegWpAmVLYqyU9EgKQbhRgdP9cdBqj3DGh0KmwbF5vLpKpkazAdCfFgnccpYP3H5WWkg7LQbN40xTMG_d3UeR4sePjT8k7tRD6j/s1600/Selection_020.png" /></a><br />
<u>Output</u><br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRaw0IDPoZ0lEu-UJPtb07TbT6ghsWmrapGC8LZfj3n7nHsPe7YGgqnipv90agpIHgfGfx78vTf6ZFP6Ult6Upzwjfy_Ret2icsSu6L5folE4L2MjmvngEcFDhnuPOiFsEVviHHzmLaELn/s1600/Selection_021.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRaw0IDPoZ0lEu-UJPtb07TbT6ghsWmrapGC8LZfj3n7nHsPe7YGgqnipv90agpIHgfGfx78vTf6ZFP6Ult6Upzwjfy_Ret2icsSu6L5folE4L2MjmvngEcFDhnuPOiFsEVviHHzmLaELn/s1600/Selection_021.png" /> </a><br />
Here the exception is because of private constructor. Since <i><b>public/protected</b></i> constructors are not allowed inside an enum, the default access scope of a constructor is <i><b>private</b></i> inside an enum. So it fails to instantiate directly.<br />
Let's try by modifying the access scope of constructor.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUXYHYhd6flEEF41AL_U-5mN_QDCx_MOX5xxkz1midJ-PAbXMJJ9b5z96ymX_NFI9PCOgA6RtuQCBxxJziSV2Gd-aUFH-gqm2mkFqWtmcUsiW3K29g93T06YSAX6qPXBiZ6PaTZ9uO9f33/s1600/Selection_022.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUXYHYhd6flEEF41AL_U-5mN_QDCx_MOX5xxkz1midJ-PAbXMJJ9b5z96ymX_NFI9PCOgA6RtuQCBxxJziSV2Gd-aUFH-gqm2mkFqWtmcUsiW3K29g93T06YSAX6qPXBiZ6PaTZ9uO9f33/s1600/Selection_022.png" /></a> <u>Output </u><br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjk_x9gYZK20VOiiz40oHU4KA0c8Oj-E3YP28KIV6-z5PcCiL9sJutduK7w2jJd1JsDmx54S15lyLcs1XJGlJGFRbb6qjR-7f0AD4orxNY4UG8J1abiuCdqf6Yf3ReiuHvEncLiGtksAcmT/s1600/Selection_024.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjk_x9gYZK20VOiiz40oHU4KA0c8Oj-E3YP28KIV6-z5PcCiL9sJutduK7w2jJd1JsDmx54S15lyLcs1XJGlJGFRbb6qjR-7f0AD4orxNY4UG8J1abiuCdqf6Yf3ReiuHvEncLiGtksAcmT/s1600/Selection_024.png" /></a><br />
Now this time the exception is because, inside <i><b>java.lang.reflect.Constructor.newInstance(Object ... initargs)</b></i>, there is a condition check like below :<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinhFhzyqDdKCxZMw9uGpx1Ydvueqw25N9J9Yucx3URrWNou0j8OdTpeMtMNDOAnm-ASXoEk9kGp8bEkEu6X926CYNQCOybud7G0ksweq8UT7CvryGR_RFbzVKccIfhjWiJnDXqZjL_XX-z/s1600/Selection_025.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinhFhzyqDdKCxZMw9uGpx1Ydvueqw25N9J9Yucx3URrWNou0j8OdTpeMtMNDOAnm-ASXoEk9kGp8bEkEu6X926CYNQCOybud7G0ksweq8UT7CvryGR_RFbzVKccIfhjWiJnDXqZjL_XX-z/s1600/Selection_025.png" /></a><br />
So there is no way to instantiate an enum using reflection.<br />
<br />
Let's try to make copy of an enum instance.<br />
<u>Test class</u><br />
<u><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrnrfmDDVkjC-CzFvrqDuW9MidxpOwHCg-38Xf216Xzeekdb5i-Sts-_clBbBsJrGyYOBOLTDPgqL7t0TCN6dTTJxiecmT7VU_7A8jq9IRZ2IXC0VJCt0_MwKnH0SDUXtz9O9H6clpnNU9/s1600/Selection_027.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrnrfmDDVkjC-CzFvrqDuW9MidxpOwHCg-38Xf216Xzeekdb5i-Sts-_clBbBsJrGyYOBOLTDPgqL7t0TCN6dTTJxiecmT7VU_7A8jq9IRZ2IXC0VJCt0_MwKnH0SDUXtz9O9H6clpnNU9/s1600/Selection_027.png" /></a> Output</u><br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcrGxyGIBAtxnD3B6adIfYnd4v4WjyMvDDUHKKkBBEEqPynjjMMZfA_8WKZSyeBv0iexSXJvcxf-x26edXb44iUJCgJXZUCbr8qcIBs3jb_wlUIjjcUbeI-BZmaHpDLWLqBZXM53AMB68T/s1600/Selection_028.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcrGxyGIBAtxnD3B6adIfYnd4v4WjyMvDDUHKKkBBEEqPynjjMMZfA_8WKZSyeBv0iexSXJvcxf-x26edXb44iUJCgJXZUCbr8qcIBs3jb_wlUIjjcUbeI-BZmaHpDLWLqBZXM53AMB68T/s1600/Selection_028.png" /> </a><br />
Now you can observe few things:<br />
- hash code f both the objects are same<br />
- state of the object got changed after it being serialized, but the changes are reflected in the deserialized object. So it is clear that the state of an enum instance is not serialized but the name by calling java.lang.Enum.name(). And while deserializing it gets only the name of the instance and by calling java.lang.Enum.valueOf() method it gets the actual enum instace.<br />
<i><br /></i>
<span style="color: blue;"><i>Conclusion : <b>enum</b> type is a special class which can not be instantiated outside of the enum class in all possible way.</i></span><br />
<br />
<br />
<span style="color: blue;"><span style="color: black;">Please feel free to give your comment/suggestion. Thank you.</span> </span></div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-25009761754653767762016-08-16T14:01:00.003-07:002016-08-17T06:20:59.883-07:00Implement Singleton class in an efficient way<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
<b>Singleton design pattern</b></h3>
This is one of the creational patterns described by <a href="https://en.wikipedia.org/wiki/Design_Patterns" target="_blank">GoF</a>. This pattern ensures that a class must have one and only one instance provided a global access point to it and also with lazy initialization (initialization on first use).<br />
<br />
So, to meet the above requirements, few steps of implementation are coming into our mind :<br />
<ul style="text-align: left;">
<li>define private no-argument constructor</li>
<li>declare private static variable of the class type as instance and initialize</li>
<li>define a public static method as access point of the instance and return the instance</li>
</ul>
<div>
<u>Approach - 1</u> (Eager Initialization)</div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLHA24JzSQw8gN6V58IGSwBLUpRu2msnL64igCNRO_zOpM1CKYsCf4JZt_wnOe19ygNA19WtGXKgZNxWvVvKkgJ47pJtsRFJ_qM7T5HniROJw0gfVqvjg-SzTCWUmVSAkokzC6IbBaaO3c/s1600/Selection_003.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLHA24JzSQw8gN6V58IGSwBLUpRu2msnL64igCNRO_zOpM1CKYsCf4JZt_wnOe19ygNA19WtGXKgZNxWvVvKkgJ47pJtsRFJ_qM7T5HniROJw0gfVqvjg-SzTCWUmVSAkokzC6IbBaaO3c/s1600/Selection_003.png" /></a><br />
<div>
<div>
This is the simplest implementation of a singleton class. But the concerns here are :</div>
<div>
1. Eager initialization</div>
<div>
2. Missing exception handling if there is chances of getting any exception during object construction</div>
<div>
<br /></div>
</div>
<div>
<u>Approach - 2</u> (Eager Initialization with Exception handling)</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaIJ81_Jbaqo5GXx0pnOBy495oo0m9q27m-IOLHG7i6tl4CNXRcuOLrxoh18OvV3E8zgdK2J-Au8RFF0yEpABlSq7ejNtLEbsYjtCHusx8SnQJWKMcLsH7yMCoSffcTX9rzUPt1GelQZVn/s1600/Selection_004.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaIJ81_Jbaqo5GXx0pnOBy495oo0m9q27m-IOLHG7i6tl4CNXRcuOLrxoh18OvV3E8zgdK2J-Au8RFF0yEpABlSq7ejNtLEbsYjtCHusx8SnQJWKMcLsH7yMCoSffcTX9rzUPt1GelQZVn/s1600/Selection_004.png" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Here the exception handling is included but still is an eager initializsation. To achieve lazy initialization, we have to instantiate the object on demand (on first access). </div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<u>Approach - 3</u>(Lazy Initialization with Exception handling)</div>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmyuDeTx_mV24D_1PCQjsMAgsdk73Qz4jE5hv4tv7zhdnMes3UQak6CGcFRfeLTzpwwNFmziSvniklNK0JR4rudr3b_OjLMevtBTxgChsiEsH1TgJEGR4Z_OdH2x17nFz5ecUp-SZsdgUV/s1600/Selection_005.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmyuDeTx_mV24D_1PCQjsMAgsdk73Qz4jE5hv4tv7zhdnMes3UQak6CGcFRfeLTzpwwNFmziSvniklNK0JR4rudr3b_OjLMevtBTxgChsiEsH1TgJEGR4Z_OdH2x17nFz5ecUp-SZsdgUV/s1600/Selection_005.png" /></a></div>
<div>
<br /></div>
<div>
Here both above concerns are addressed (lazy initialization and exception handling) and the code looks fine. But it doesn't mean this is the efficient implementation. This implementation has so many concerns :</div>
<div>
1. Not thread safe</div>
<div>
2. Can be broken by serialisation if the class is serializable </div>
<div>
<br /></div>
<div>
For thread safe, that we can achieve through<i style="font-weight: bold;"> </i>synchronisation<i style="font-weight: bold;"> </i>(either by defining <i style="font-weight: bold;">synchronized </i>method or synchronized block with double check lock while instantiating the object). </div>
<div>
<u>Approach - 4</u></div>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXFSTTMYOEe52yExFd49E3zdp-G2NDXP01gFiqypOVj-D39SBW9LCSlWNpbTTPide7TWFW1mfoFOilxMWcmBUUcFnT4KSz7j_fPaEXT55HlEGsOvfL9Vx6FfMDSi4uCrG7X6PoIdd-SZEf/s1600/Selection_006.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXFSTTMYOEe52yExFd49E3zdp-G2NDXP01gFiqypOVj-D39SBW9LCSlWNpbTTPide7TWFW1mfoFOilxMWcmBUUcFnT4KSz7j_fPaEXT55HlEGsOvfL9Vx6FfMDSi4uCrG7X6PoIdd-SZEf/s1600/Selection_006.png" /></a></div>
<div>
And in the previous approach (Approach - 1 and Approach - 2), during the eager initialization, the implementation is completely safe in multi threaded environment as the object is instantiated during the class loading. But we can't achieve the lazy initialization in this approach. To overcome this <b>Bill Pugh </b>came up with a new approach to create singleton class using a static inner class. </div>
<div>
<u>Approach - 5 </u>(Bill Pugh's approach using static inner class to achieve thread safety and lazy loading)</div>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRlcpgosNtKO-ByKaXYGt0Zs_lOaAMAW9e73M_vUFGWVK7LWKvXK4tahixSAEJGrkGc0mD3pey8ApwFjtot19QDXcMBr6lKj4kdvA9uTVjEp3lOwo-17VhUM8nIKTCGoQu_Q2GNeQrKk-H/s1600/Selection_007.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRlcpgosNtKO-ByKaXYGt0Zs_lOaAMAW9e73M_vUFGWVK7LWKvXK4tahixSAEJGrkGc0mD3pey8ApwFjtot19QDXcMBr6lKj4kdvA9uTVjEp3lOwo-17VhUM8nIKTCGoQu_Q2GNeQrKk-H/s1600/Selection_007.png" /></a></div>
<div>
Here <b>SingletonHelper</b> class is a static inner class. And this will not be loaded with the <b>Singleton</b> class. When ever the <b><i>Singleton.getInstance() </i></b>method will be invoked, and the <i style="font-weight: bold;">SingletonHelpet.instance </i>will be access for the first time, the helper class will be loaded at the same time. Using this approach the lazy initializaton is achieved easily and also thread safe.</div>
<div>
<br /></div>
<div>
Now, let's discuss about the other concern - "<i>Can be broken by serialisation if the class is serializable"</i>. Here we can apply Java's magic method trick to resolve these kind of problems. Java provided some hidden and tricky method ( <a href="https://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html#5903" target="_blank"><i>readResolver()</i></a> ) for developer to replace the deserialized object with the required object.</div>
<div>
<u>Approach - 6 </u></div>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLI9Fa1NvlV-SktpA2tbEpX13c6oJAe54W76jPMxc7Rd6RlRAzcSeI4XPDG31G7rj0q9P5V9XtbVjTlyiiWNQ_87vzzwF1VIClHNhym2MoDIgjGIQ54krPKxDMkY2DFu6fY7NmKt6tGkpu/s1600/Selection_010.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLI9Fa1NvlV-SktpA2tbEpX13c6oJAe54W76jPMxc7Rd6RlRAzcSeI4XPDG31G7rj0q9P5V9XtbVjTlyiiWNQ_87vzzwF1VIClHNhym2MoDIgjGIQ54krPKxDMkY2DFu6fY7NmKt6tGkpu/s1600/Selection_010.png" /></a></div>
<div>
The <i>readResolve() </i>is called when <i>ObjectInputStream </i>reads the object from stream and trying to return to the caller. Here we have returned the <b><i>SingletonHelper.instance</i></b>, so the deserialized object will be replaced by this instance.</div>
<div>
<br /></div>
<div>
After all these approach, you might have decides already to go with the Approach - 6 as it overcomes all the concerns :</div>
<div>
1. No more eager initialization</div>
<div>
2. Thread safe in multi threaded environment</div>
<div>
3. Safe with Serialization</div>
<div>
<br /></div>
<div>
After all looks fine, now we will discuss about the real devil for all these approaches that is Java <i><b>Reflection</b>. </i>This is the mechanism by which any kind of class (even with private constructor, private members)<b style="font-style: italic;"> </b>are also can be accessed by creating new instance of that class. So the above approach can be broken with this mechanism. </div>
<div>
<br /></div>
<div>
To overcome this, we have to go for the best approach for implementing singleton class proposed by <a href="http://www.informit.com/authors/bio/8b620cf7-c360-4ee1-9b55-c7f96e7f0d18" target="_blank">Joshua Bloch</a> in <a href="http://www.informit.com/store/effective-java-9780132639491" target="_blank">Effective Java</a> <b>"a single-element enum type is the best way to implement a singleton"</b>.</div>
<div>
<u>Approach - 7</u> (The best for Serialization/Reflection attacks but eager initialization)<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY-48sV4DBGzALwv_SJnQQhaTP6x0tOI3DPFi615NbwDrp6zUsH8IRJ3pd8y2A2toHLq_v7ATgY6YOegV3fFOQt155wL7eDX0ARuNJMjsxb3f9nFy8hz8RAEvaHrKRCJQcE82SPJTTrBf4/s1600/Selection_012.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY-48sV4DBGzALwv_SJnQQhaTP6x0tOI3DPFi615NbwDrp6zUsH8IRJ3pd8y2A2toHLq_v7ATgY6YOegV3fFOQt155wL7eDX0ARuNJMjsxb3f9nFy8hz8RAEvaHrKRCJQcE82SPJTTrBf4/s1600/Selection_012.png" /></a> </div>
<div>
</div>
<div>
Here in this above example I have demonstrated the same previous required singleton class using enum type. </div>
<div>
<br /></div>
<div>
The below are the reasons why this approach is the best to implement a singleton class.</div>
<div>
1. Java gives guarantee that enum can not be broken by Reflection API : We can not create </div>
<div>
instance of an enum using Reflection API</div>
<div>
2. Serialization process is different for enum than a normal class : During serialization, </div>
<div>
ObjectOutputStream writes the value returned by enum constant's name() method. And to </div>
<div>
deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the </div>
<div>
deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing </div>
<div>
the constant's enum type along with the received constant name as arguments. </div>
<div>
<i> Ref : <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum" target="_blank">Serialization of Enum Constants</a></i></div>
<div>
<br />
Above all benefits, still enum type approach has the concern of eager initialization. We can not achieve Lazy Initialization in this approach but more robust for serialization/reflection attack. If you have more concerns about eager initialization, then you can go with Approach - 6 but again the devil (reflection API) can pull it down.<br />
<br />
<br />
<br />
Please feel free to give your comment/suggestion. Thank you.</div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-3520804379999047582016-08-08T11:11:00.002-07:002016-08-08T11:48:31.745-07:00Power of Lambda Expression and Function Programing in Java 8<div dir="ltr" style="text-align: left;" trbidi="on">
<i>Functional Programing</i> is the most powerful concept introduced in Java 8. And this can be only achieved by<i> <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" target="_blank">Lambda Expression.</a></i><br />
<br />
Now, you may get W2H in your mind. Hold on, "W2H" is not any chemistry terminology. I just refer as W2H means (What, Why and How). I mean you are now thinking about "What is Lambdas, Why Lambdas, and How to use Lambdas ?".<br />
<br />
Before discussing on Lambdas in details, I just want you to feel the power of it using some examples. Each example here I have prepared with 2 snippet of codes, first is <b>without Java 8</b> and followed by <b>Java 8 style</b> implementation.<br />
<br />
I have a list of employees here with members(id, name, salary, doj, location, dept, permanent/contractor).<br />
<span style="color: #e06666;">Employee{empId='EMP001', name='Mr. Alpha', salary=24000.0, deptName='Product Development', isPermanent=true, doj=Mon Dec 12 00:00:00 IST 2011, location='Chennai'}<br />Employee{empId='EMP002', name='Mr. Beta', salary=43000.0, deptName='Support', isPermanent=false, doj=Mon Jul 02 00:00:00 IST 2012, location='Chennai'}<br />Employee{empId='EMP003', name='Mr. Gama', salary=66000.0, deptName='Product Development', isPermanent=false, doj=Mon Dec 30 00:00:00 IST 2013, location='Bangalore'}<br />Employee{empId='EMP004', name='Mr. Theta', salary=54000.0, deptName='Quality Engineer', isPermanent=true, doj=Wed Sep 12 00:00:00 IST 2012, location='Hyderabad'}<br />Employee{empId='EMP005', name='Mr. Delta', salary=58000.0, deptName='Support', isPermanent=true, doj=Tue Apr 23 00:00:00 IST 2013, location='Hyderabad'}</span> <br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIsKl2qgHoFzWeZvvfnjgwZgi7LucNz4Kv1KvLEZ_ztDMrx6_si26KjSJH372u2aZmnhUK9Vl3iFukUu1KY6dgA2sIJxWm-876vFUTt_ULsrQ1L5F7O09JhczyGzfy-N8iSbZK6PXGU0Zf/s1600/sc1_1.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIsKl2qgHoFzWeZvvfnjgwZgi7LucNz4Kv1KvLEZ_ztDMrx6_si26KjSJH372u2aZmnhUK9Vl3iFukUu1KY6dgA2sIJxWm-876vFUTt_ULsrQ1L5F7O09JhczyGzfy-N8iSbZK6PXGU0Zf/s1600/sc1_1.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhErKHQICjTMGtSteapVmP9WdvZv4q1CWf9Y88QR5VTUpi0Fr0EyfTR94Ie094r4TQwCs4GBk3oPl3NFg97wtB_hWIWc8n_bjLQsG4qxDKtRHQ4daV-zT3k081qiLLlkVvMZVwjMvte1Xg8/s1600/sc2_1.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhErKHQICjTMGtSteapVmP9WdvZv4q1CWf9Y88QR5VTUpi0Fr0EyfTR94Ie094r4TQwCs4GBk3oPl3NFg97wtB_hWIWc8n_bjLQsG4qxDKtRHQ4daV-zT3k081qiLLlkVvMZVwjMvte1Xg8/s1600/sc2_1.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF9EfIOaXuxk32LHXLcE25ioq78drUHVPeOyMi9gfZGfZRBsV2mOZX1rZlcejgQxmUf8qJ6Rj8tjPd59hqpvhjwaaKEj8mSmxdw6Dblrw-yjxUgGtHIfGAKFJgaMFwx3Y0tqMy00x4ePFI/s1600/sc3_1.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF9EfIOaXuxk32LHXLcE25ioq78drUHVPeOyMi9gfZGfZRBsV2mOZX1rZlcejgQxmUf8qJ6Rj8tjPd59hqpvhjwaaKEj8mSmxdw6Dblrw-yjxUgGtHIfGAKFJgaMFwx3Y0tqMy00x4ePFI/s1600/sc3_1.png" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQT6uW7xctxV1qlw2Rf14jwS_BCZ1qsKIRKKZKDo4aeF0NLDNrEeau3NOAZkAOix41C7SL7g-WPP1qwajYQQZhn0-3HR8QA80AataDXUgv9VmpNJemqSZPwzSNlOrRCpjsqe3Xyr2HcH9u/s1600/sc4_1.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQT6uW7xctxV1qlw2Rf14jwS_BCZ1qsKIRKKZKDo4aeF0NLDNrEeau3NOAZkAOix41C7SL7g-WPP1qwajYQQZhn0-3HR8QA80AataDXUgv9VmpNJemqSZPwzSNlOrRCpjsqe3Xyr2HcH9u/s1600/sc4_1.png" /> </a>These examples are demonstrated the power of Lambda Expression and Functional style of programming. We will discuss in depth how it works for better understanding. </div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Stay tuned for more updates.....</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-12279644070626694622016-08-05T11:29:00.004-07:002016-08-05T11:29:25.430-07:00Folder Watcher using java.nio.file.WatcherService<div dir="ltr" style="text-align: left;" trbidi="on">
A simple folder inspector/watcher which logs the user action into a file.<br />
User actions includes :<br />
- Create<br />
- Modify<br />
- Delete<br />
<br />
Here we are going to discuss on few new classes introduced as part of java.nio package with Java 1.7<br />
<i><b>- java.nio.file.Path : </b>This represents typically represent a system dependent file path to locate a file in a file system.</i><br />
<i><b>- java.nio.file.WatchService : </b>It a service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.</i><br />
<i><b>- java.nio.file.WatchEvent : </b>An event for an object that is registered with a WatchService.</i><br />
<i><b>- java.nio.file.WatchKey : </b>A token representing the registration of a watchable object with a WatchService. Here <b>Path </b>is a watchable object which will be watched by WatchService.</i><br />
<i><b>- java.nio.file.FileSystems : </b>Factory methods for file systems.</i><br />
<i><b>- java.nio.file.FileSystem : </b>It is an interface to a file system and is the factory for objects to access files and other objects in the file system.</i><br />
<i><br /></i>
<i><u>FolderWatcher.java</u></i><br />
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZpsyWsbXfCPBOxghjL2vJOUDH48YOerQNhWC_OumV2TUDrb8td7FMVJinIUQjZtiSSMN3Z0xXb-Enrnu4cVKewczMVl-L3ycOW5RPDbepIBSc7K_SzWDejt14KNusWOfId51DTbpReF1i/s1600/final.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZpsyWsbXfCPBOxghjL2vJOUDH48YOerQNhWC_OumV2TUDrb8td7FMVJinIUQjZtiSSMN3Z0xXb-Enrnu4cVKewczMVl-L3ycOW5RPDbepIBSc7K_SzWDejt14KNusWOfId51DTbpReF1i/s1600/final.jpg" /></a><span style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;">Output:</span><span style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em; text-align: left;"><span style="font-size: x-small;">dir-log.txt</span><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgy6_9xe2Ljdxi3aS3y_IDX2i0iWN4HwMx7ZImsg5sI4wB8kB-V5yKxXLj7_tpo2_ttt8OiVwrhviVn50-DZTk3qZpWJAlYHsboeSy86UM6yBg2OF7CMWsjq0u6I6AG4ptGXJV6xSgDeAPq/s1600/Screenshot+from+2016-08-05+23-52-26.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="97" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgy6_9xe2Ljdxi3aS3y_IDX2i0iWN4HwMx7ZImsg5sI4wB8kB-V5yKxXLj7_tpo2_ttt8OiVwrhviVn50-DZTk3qZpWJAlYHsboeSy86UM6yBg2OF7CMWsjq0u6I6AG4ptGXJV6xSgDeAPq/s640/Screenshot+from+2016-08-05+23-52-26.png" width="640" /></a></span></div>
<i><u><br /></u></i>
<br /></div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-64665889778228287342016-04-07T05:30:00.002-07:002016-04-07T09:18:01.541-07:00Sudoku Solver : Solve any level of Sudoku <div dir="ltr" style="text-align: left;" trbidi="on">
<b>Sudoku Solver :</b><br />
This is implemented by simple back-tracking algorithm (<a href="https://en.wikipedia.org/wiki/Backtracking" target="_blank">Backtracking Ref</a>) in Javacript.<br />
<br />
Simple steps to solve your Sudoku :<br />
1. Download the file <span style="color: #f1c232;"> </span><a href="https://drive.google.com/file/d/0B70lEzOsSIZmWno2UjM1Q2ZQOVk/view?usp=sharing" target="_blank">Sudoku Solver</a><br />
2. Make sure the downloaded file should be save as .html file, else rename it to <filename>.html<br />
3. Open downloaded file in browser<br />
<br />
<b>Algorithm :</b><br />
Input : A 2D 9x9 array <i><b>(arr)</b></i> with having valid and solvable input values.<br />
Valid - No number (1-9) is repeated in a same row, same column or same 3x3 box.<br />
Solvable - Even though the input is valid, but there is a chance of not having the solution for a particular input if that is randomly generated.<br />
<br />
<i><b>boolean solveSudoku(arr[9][9])</b></i><br />
<i>Find an EMPTY cell (r, c) from the array </i><br />
<i>If no EMPTY cell found then</i><br />
<i> return TRUE ; // i.e the array is filled i.e. solved</i><br />
<i> else</i><br />
<i> for <b>num</b> from 1 to 9</i><br />
<i> check if arr[r][c] is SAFE to put <b>num</b></i><br />
<i><b> </b>if SAFE then</i><br />
<i> arr[r][c] = num; //update cell with num, consider this is a part of the goal</i><br />
<i> // call recursively </i><i><b>solveSudoku(arr) </b>to solve next EMPTY cell</i><br />
<i> result = </i><i>solveSudoku(arr) </i><br />
<i> if result is FALSE then // No solution exist with arr[r][c] = num </i><br />
<i> arr[r][c] = 0; // Revert back the considered solution</i><br />
<i> else</i><br />
<i> return TRUE; // We reached at the goal by taking arr[r][c] =num</i><br />
<i> end for</i><br />
<i> return FALSE; // No solution exists, since no number from 1 to 9 can be placed at(r,c)</i><br />
<br />
For SAFE checking :<br />
<b><i>boolean isSafe(arr[9][9], roe, col, num)</i></b><br />
<i><b> </b>if num is present in same row or same column or same inner 3x3 box then</i><br />
<i> return FALSE</i><br />
<i> else</i><br />
<i> return TRUE</i><br />
<br />
<b><i><br /></i></b>
<i>Get <a href="https://github.com/PrabhatKJena/CoreAlgoDST/blob/master/src/main/java/edu/pk/algo/backtracking/SudokuUI.html" target="_blank">Source Code</a> here.</i><br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" height="356" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLtRLxpGwYEX506ibIzCT_VeFw9zTcM589EjetXbcJ1HBpo0Jn8jaPRoiGRjI8GieXh9vX1eCr_kFmXKrbgGazeAIA-A2JGVKB8GhC6NEF_mzv7KzwmZJBHAPr60WIbV7vu8QaJNaSSou_/s640/sudoku_1.jpg" width="640" /></div>
<br />
<br />
<i style="background-color: #fff9ee; color: #222222; font-family: georgia, utopia, 'palatino linotype', palatino, serif; font-size: 15.4px; line-height: 21.56px;"><span style="color: #e69138;">Thank You for Visiting the blog.</span></i></div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-20310394541615773062016-04-02T08:39:00.002-07:002016-04-04T00:49:08.756-07:00Text to Speech in Java<div dir="ltr" style="text-align: left;" trbidi="on">
Converting text-to-speech is very simple, just by using <b><i>FreeTTS</i></b> library.<br />
<br />
<div>
Include library by maven dependency :</div>
<div>
<dependency></div>
<div>
<span class="Apple-tab-span" style="white-space: pre;"> </span><groupId>org.mobicents.external.freetts</groupId></div>
<div>
<span class="Apple-tab-span" style="white-space: pre;"> </span><artifactId>freetts</artifactId></div>
<div>
<span class="Apple-tab-span" style="white-space: pre;"> </span><version>1.0</version></div>
<div>
</dependency></div>
<div>
<br /></div>
<div>
OR</div>
<div>
Download library (jar file) from <a href="https://sourceforge.net/projects/freetts/files/FreeTTS/FreeTTS%201.2.2" target="_blank">here</a> and include into project directly.<br />
<div>
<br /></div>
</div>
<div>
<b>How to use FreeTTS API ?</b></div>
<div>
Step - 1 : Get the instance of <i>com.sun.speech.freetts.VoiceManager </i>class.</div>
<div>
VoiceManager provides access to all voices available in FreeTTS</div>
<div>
<i> <span style="color: blue;">VoiceManager voiceManager = VoiceManager.getInstance();</span></i></div>
<div>
<br /></div>
<div>
Step - 2 : Get <i>com.sun.speech.freetts.Voice </i>instance using <i>voiceManager</i> by supplying the voice name</div>
<div>
<i><span style="color: blue;">Voice voice = voiceManager.getVoice("kevin16");</span></i></div>
<div>
Here <i>"kevin16"</i> is one of the voice name available in FreeTTS library.</div>
<div>
You can also get all available voice names like below :</div>
<div>
</div>
<div>
<i> <span style="color: blue;">Voice voices1[] = voiceManager.getVoices(); </span></i></div>
<div>
<i><span style="color: blue;"> System.out.println("Available Voices");</span></i></div>
<div>
<i><span style="color: blue;"> for (int i = 0; i < voices1.length; i++)</span></i></div>
<div>
<i><span style="color: blue;"><span class="Apple-tab-span" style="white-space: pre;"> </span> System.out.println(voices1[i].getName());</span></i></div>
<div>
<i><br /></i></div>
<div>
Step - 3 : Set voice rate (i.e no of words per minute)</div>
<div>
<i><span style="color: blue;">voice.setRate(120);</span></i></div>
<div>
<i><span style="color: blue;"><br /></span></i></div>
<div>
Step - 4 : call speak( ) method by providing the text to speech</div>
<div>
<i><span style="color: blue;">voice.speak("<text to speech>");</span></i></div>
<div>
<span style="color: blue; font-style: italic;"> </span>This speak( ) is overloaded to support various types of inputs like text, inputStream etc.</div>
<div>
You can also read a file by providing the fileInputStream as below : </div>
<div>
<i><span style="color: blue;">FileInputStream fileInputStream = new FileInputStream("d:/ttsInput.txt");</span></i></div>
<div>
<i><span style="color: blue;"> voice.speak(fileInputStream);</span></i></div>
<div>
<br /></div>
<div>
Here is the complete code to convert a text file to speech : </div>
<div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;">import com.sun.speech.freetts.Voice;</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;">import com.sun.speech.freetts.VoiceManager;</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;">import java.io.FileInputStream;</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;">public class TextToSpeech {</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> private static final String voiceName = "kevin16"; // this is one of the voice name available in default</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> private static void doSpeak() {</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> try {</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> VoiceManager voiceManager = VoiceManager.getInstance();</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> Voice voice = voiceManager.getVoice(voiceName);</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> if (voice != null) {</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> voice.allocate();</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> // Set 120 words per minute</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> voice.setRate(120);</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> FileInputStream fileInputStream = new FileInputStream("d:/ttsInput.txt");</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> voice.speak(fileInputStream);</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> voice.deallocate();</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> } else {</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> System.out.println("No Voice Available");</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> }</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> } catch (Exception e) {</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> e.printStackTrace();</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> }</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> }</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> public static void main(String[] args){</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> doSpeak();</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;"> }</span></div>
<div>
<span style="color: blue; font-family: "courier new" , "courier" , monospace;">}</span></div>
<div>
<br /></div>
</div>
<div>
Here is a demonstration of a <b>Speaking Alarm Clock </b>application using this <b>FreeTTS </b>library.</div>
<div>
Functionalities of application : </div>
<div>
1. class <i>AlarmClock<b> : </b></i>This class creates the alarm clock UI using Java Swing API, having feature to set alarm for a specific time and triggers the TimeSpeaker to speak the time on the time for which alarm is set.</div>
<div>
2. class <i>TimeSpeaker : </i>This class converts any time into word form</div>
<div>
<i> e.g 05:15 -> quarter past five</i></div>
<div>
<i> 03:30 -> half past three</i></div>
<div>
<i> 11:40 -> twenty minutes to twelve</i></div>
<div>
<i>3. class TextToSpeech : </i>This is the class responsible of converting text to speech using freetts (Free Text To Speech) library</div>
<div>
<span style="color: blue;"><br /></span></div>
<div>
<span style="color: blue;">Download OR fork complete project from <a href="https://github.com/PrabhatKJena/SpeakingAlarmClock" target="_blank">here</a> .</span></div>
<div>
<br /></div>
<div>
<i style="color: #222222; font-family: georgia, utopia, 'palatino linotype', palatino, serif; font-size: 15.4px; line-height: 21.56px;"><br /></i></div>
<div>
<i style="font-family: georgia, utopia, 'palatino linotype', palatino, serif; font-size: 15.4px; line-height: 21.56px;"><span style="color: #e69138;">Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. </span></i></div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-52752195832911965752016-03-10T09:15:00.000-08:002019-08-20T08:42:35.174-07:00Be Careful while overriding hashCode() and equals() methods inside an Inner class<div dir="ltr" style="text-align: left;" trbidi="on">
I know couple of questions coming into your mind before coming here.<br />
1. What is the new or different things while overriding hashCode() and equals() methods inside an inner class?<br />
2. Is there really any difference while overriding in a normal class and an inner class?<br />
<br />
To answer these questions, let's see an example :<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfh9tLlkG8j8KR1F9GSAE_Mw8mT_Lo9e8M7TYw0j2A2IPnaCw8Yy4BCJK04kslaI3F6lzSpedyYfMdkcyvAxEJ82wwUxFWswx5wcgG4hBl-pdgYUn4tAoc5XmhSOLAv6xPlnnXJF5VXfcO/s1600/ss1.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfh9tLlkG8j8KR1F9GSAE_Mw8mT_Lo9e8M7TYw0j2A2IPnaCw8Yy4BCJK04kslaI3F6lzSpedyYfMdkcyvAxEJ82wwUxFWswx5wcgG4hBl-pdgYUn4tAoc5XmhSOLAv6xPlnnXJF5VXfcO/s1600/ss1.jpg" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUe9F8IBviZEXLVoCJKZW5tTyZbLisLNcBd3jxeSh3ZwTBKvtRyc9g5e_V5hi5x_a10zDvYIV8IOD0JdNDdYT0Tx3gujKeuM5i5SJlfZdvSnOQbXMeN5auYqfKsPOBG6NHYuArgTjWbD36/s1600/ss2.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUe9F8IBviZEXLVoCJKZW5tTyZbLisLNcBd3jxeSh3ZwTBKvtRyc9g5e_V5hi5x_a10zDvYIV8IOD0JdNDdYT0Tx3gujKeuM5i5SJlfZdvSnOQbXMeN5auYqfKsPOBG6NHYuArgTjWbD36/s1600/ss2.jpg" /></a></div>
<b> Output</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLakMsJc_LnuEVVilX4OM9JB7VxYuyLqN4JrsLwLSr4IHmS1uiRroWupJnT7K47RO9NLrkCOy_-7njYFoL-SHoW24f0uSYHLGJo0srRQg2jpoGWulSmM0FtCtcD20plcntlH7vl750sGPK/s1600/ss3.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLakMsJc_LnuEVVilX4OM9JB7VxYuyLqN4JrsLwLSr4IHmS1uiRroWupJnT7K47RO9NLrkCOy_-7njYFoL-SHoW24f0uSYHLGJo0srRQg2jpoGWulSmM0FtCtcD20plcntlH7vl750sGPK/s1600/ss3.jpg" /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLakMsJc_LnuEVVilX4OM9JB7VxYuyLqN4JrsLwLSr4IHmS1uiRroWupJnT7K47RO9NLrkCOy_-7njYFoL-SHoW24f0uSYHLGJo0srRQg2jpoGWulSmM0FtCtcD20plcntlH7vl750sGPK/s1600/ss3.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Here observe the output carefully, we have added 4 task executors into the set and then executing all one by one. But only 2 executors are executed. Because here <b><i>taskExecutor1 </i></b>and <b><i>taskExecutor3</i></b> having same data/state and the <b>hashCode()</b> and <b>equals() </b>method identify both the objects as equal. Similarly for <b><i>taskExecutor2</i></b> and <b><i>taskExecutor4</i></b> also.<br />
<br />
Even though the state of the executor objects <b><i>taskExecutor1</i></b> and <b><i>taskExecutor2</i></b> are same, but they are associated with 2 different outer class objects <b><i>service1</i></b> and <i style="font-weight: bold;">service2 </i>having different state/data. As a result somewhere if the inner class object depends on the outer class object's state, it may behave different. So the inner class objects should not be treated as equal objects if they are associated with different outer class objects regardless of its own state.<br />
<br />
Let's modify the overriden equals() method inside the inner class in such a way that it should check the equality of the outer class objects also.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCRg3eDzUsrHcvjoe2282ywwOhmTiqd603fWYr7zSTd08j1dkHTifmZKgVU5u2G8REXYKmSBZX9grEPfk5xtQ-_c31Ih2gelFfe54p8QFTj0wTzz3VXnD2TQW6s4eMXZphV5d-wiqwqshd/s1600/ss4.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCRg3eDzUsrHcvjoe2282ywwOhmTiqd603fWYr7zSTd08j1dkHTifmZKgVU5u2G8REXYKmSBZX9grEPfk5xtQ-_c31Ih2gelFfe54p8QFTj0wTzz3VXnD2TQW6s4eMXZphV5d-wiqwqshd/s1600/ss4.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
So while overriding equals() method inside inner class, it is most important to check the equality of the objects of the enclosed outer class. </div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Output with the modified code :</b></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtqjZ-XOwgPr1gGyfu4uhL82JgSnSiY2_edO6ydr1XrBVohhzzPs1vObmSDLcbyNZHBxMVrf7M1tMs4-km-5qr16xqIw2DSItg8DeqKc4jHpBNR5tlhom4qUQStY3nOt_LTJMVWH1EYvaC/s1600/ss5.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtqjZ-XOwgPr1gGyfu4uhL82JgSnSiY2_edO6ydr1XrBVohhzzPs1vObmSDLcbyNZHBxMVrf7M1tMs4-km-5qr16xqIw2DSItg8DeqKc4jHpBNR5tlhom4qUQStY3nOt_LTJMVWH1EYvaC/s1600/ss5.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<i><span style="color: red;"> Note : If the outer class have non-static member(s), then it is mandatory to check the equality of the objects of the enclosing outer class.</span></i></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<br />
<div style="text-align: left;">
<span style="background-color: #fff9ee; color: #222222; font-family: "georgia" , "utopia" , "palatino linotype" , "palatino" , serif; font-size: 15.3999996185303px; line-height: 21.5599994659424px;"><i>Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. </i></span></div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-44514061536813346272016-02-27T22:35:00.002-08:002016-03-01T03:45:36.433-08:00ORM (Object Relational Mapping) is Not a Magic at ALL<div dir="ltr" style="text-align: left;" trbidi="on">
<b>How ORM works in background?</b><br />
From the name itself, it says that<br />
<br />
<ul style="text-align: left;">
<li>Map the object with relational database and keep the meta data(mapping informations). e.g. class against table name, fields of the class against columns of the table</li>
<li>Generate SQL on demand in background using the meta data and Java Reflection API. e.g. for saving an object it generates INSERT query corresponding to the table and fields for which the object is mapped. Similarly to find, update and delete, it generates SELECT, UPDATE and DELETE queryies respectively.</li>
</ul>
<br />
<div>
Here I have demonstrated how <i style="font-weight: bold;">Hibernate</i>(one of the ORM implementations)<i style="font-weight: bold;"> </i>works internally using Java core API(including Reflection API) and JDBC API <b><span style="color: red;">(not Hibernate API).</span></b> <i><span style="color: blue;"><b>Download/Fork project from </b><a href="https://github.com/PrabhatKJena/HibernatePOC" target="_blank"><span style="color: blue;">https://github.com/PrabhatKJena/HibernatePOC</span></a></span></i></div>
<br />
First of all let's see how the code looks like when we are working with ORM.<br />
<i><b><span style="color: #6fa8dc;"><u>Test.java</u></span></b></i><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0dGnNyd-w4LkbkmKYuBP1mHBIX3850CrwsNH2IqXSJ-XRG3cFXlkcYtxijd7iA89X8CW4Pu2f12xuPa1LRqXa-7R32xlLiqp1n3fCvVLiFp5Bh64p6YZLKtVECOCfrS628c2d_i3oEH8_/s1600/sc1.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0dGnNyd-w4LkbkmKYuBP1mHBIX3850CrwsNH2IqXSJ-XRG3cFXlkcYtxijd7iA89X8CW4Pu2f12xuPa1LRqXa-7R32xlLiqp1n3fCvVLiFp5Bh64p6YZLKtVECOCfrS628c2d_i3oEH8_/s1600/sc1.jpg" /></a></div>
<div style="text-align: left;">
<b>Output:</b></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgloknvrC7N3nM3-n2NZNvo7UYk6A0kTylVS9u3zgN2xHkrGzHCPSIyapm0nxl2QxUyP0hIh2hKNhdLr_Q5Qosi0xeHPdRE5J_heyNURFsvwULRlYoEf2TtH5DCbtvUI2goKosV7NOcArZ/s1600/sc2.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgloknvrC7N3nM3-n2NZNvo7UYk6A0kTylVS9u3zgN2xHkrGzHCPSIyapm0nxl2QxUyP0hIh2hKNhdLr_Q5Qosi0xeHPdRE5J_heyNURFsvwULRlYoEf2TtH5DCbtvUI2goKosV7NOcArZ/s1600/sc2.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="color: blue;">Here you can observe the code looks like Hibernate code but there is no hibernate API used. </span></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Now let's have a look into the code in background.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRLYNOQXii5kN9WCRFLqdCoARdEz1kqG1hOrO85f4WiD_o-yng2Cy28uzrabCMxggQ95Ujiv5MzoMVXPXbNK95ZOlXEA0enhgXrQW-qNUv7GBDDDmLd7BrWtbwaPq63bYBmdy6MFCSR__i/s1600/cong.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRLYNOQXii5kN9WCRFLqdCoARdEz1kqG1hOrO85f4WiD_o-yng2Cy28uzrabCMxggQ95Ujiv5MzoMVXPXbNK95ZOlXEA0enhgXrQW-qNUv7GBDDDmLd7BrWtbwaPq63bYBmdy6MFCSR__i/s1600/cong.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
This is the config file (like hibernate-configuration) where JDBC connection details are configured. </div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6QG1vs1leTCKdmeah5QvkQdeVF3b2bsgPtqAvH1BbwG7neWp6HgrQmph5J-Ngh82h31jUgCglgK1JlzFDKingzzbIfgBGSU-nBfqY-bHqYp27YYuuriU4Ot8YIrJ1Qpq9gQYdxBLSBJ1S/s1600/an1.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6QG1vs1leTCKdmeah5QvkQdeVF3b2bsgPtqAvH1BbwG7neWp6HgrQmph5J-Ngh82h31jUgCglgK1JlzFDKingzzbIfgBGSU-nBfqY-bHqYp27YYuuriU4Ot8YIrJ1Qpq9gQYdxBLSBJ1S/s1600/an1.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNAtPrIBH0X0E1Je9mydKJVbxoVilKuZRi5phkmMx4k-2D92AYR8Mm8aliDvI7mZbASZ5dUq8NCughYjlkb1QsLkPCj2FWNN6ESqE8JTrA3rVhbq4t0doXZ7b_n0SQ1tFE8lJi1knAqyvz/s1600/an2.jpg" imageanchor="1" style="clear: left; display: inline !important; margin-bottom: 1em; margin-right: 1em; text-align: center;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNAtPrIBH0X0E1Je9mydKJVbxoVilKuZRi5phkmMx4k-2D92AYR8Mm8aliDvI7mZbASZ5dUq8NCughYjlkb1QsLkPCj2FWNN6ESqE8JTrA3rVhbq4t0doXZ7b_n0SQ1tFE8lJi1knAqyvz/s1600/an2.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
These are our custom annotations similar to <i>@Entity</i>, <i>@Column</i> in Hibernate.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAb9u7T4MBibF9fqv7-8RmmGwvHAgPGaTYiooSPRSROW0F-GYzYV90j8xXWk4bv00Ayp-u036boIQIWdsTBcjRbDcyrlcn8eg3X2dP5St6LL5ofLHUnkZDq9oal1jO3q5_W03KhqMMK7vb/s1600/confclass.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAb9u7T4MBibF9fqv7-8RmmGwvHAgPGaTYiooSPRSROW0F-GYzYV90j8xXWk4bv00Ayp-u036boIQIWdsTBcjRbDcyrlcn8eg3X2dP5St6LL5ofLHUnkZDq9oal1jO3q5_W03KhqMMK7vb/s1600/confclass.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
This is the Configuration class which is responsible for loading JDBC driver and set JDBC properties to SessionFactory (nothing but a JDBC Connection Factory)</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgq6lXzwrIDHVXVPmarwa0yyn_eOcZFKV12KjF1uZHOu-hTTq6Zy1yMzB13VyCRxuH_I0PTY4kzjbs7T3a1JpZM9pbtLUZF9i9g4DkJ12Uipx20OnXF3GfeoROI1vBsZapMcuwvZlC2cfSb/s1600/sf.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgq6lXzwrIDHVXVPmarwa0yyn_eOcZFKV12KjF1uZHOu-hTTq6Zy1yMzB13VyCRxuH_I0PTY4kzjbs7T3a1JpZM9pbtLUZF9i9g4DkJ12Uipx20OnXF3GfeoROI1vBsZapMcuwvZlC2cfSb/s1600/sf.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
This class is like a JDBC Connection factory which creates and returns JDBC Connection as a Session object.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3yi3Mm-DuAjJf6NWVLO36bKytFY6AguVdGEtxbFw1weF4BWSEahyqE-yJNkmKDf4q3gBaKq2Xq5RDKfaI_ZkEAc0sKjMLh59-kgEio_KhlS3sr75AtYFFKXZlSyaWO5H-3scxtj2J8Rhn/s1600/sess.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3yi3Mm-DuAjJf6NWVLO36bKytFY6AguVdGEtxbFw1weF4BWSEahyqE-yJNkmKDf4q3gBaKq2Xq5RDKfaI_ZkEAc0sKjMLh59-kgEio_KhlS3sr75AtYFFKXZlSyaWO5H-3scxtj2J8Rhn/s1600/sess.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
This is the important class (same as Session in Hibernate) which provides methods to persist, update, get and delete an entity.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjm_IsP0f5niFVWYS1TMbd5t2Taq03sfdAhW3HBTpEJ4JCMKuhNQDI3EYqRC7xcJuNxeKRcd9-SDK0C10rJtpKngsxR54YUVyNxwOPlpphowwMyhl9E5G7E-fgpArHqtznRujAhUViFKsNa/s1600/mappingdata.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjm_IsP0f5niFVWYS1TMbd5t2Taq03sfdAhW3HBTpEJ4JCMKuhNQDI3EYqRC7xcJuNxeKRcd9-SDK0C10rJtpKngsxR54YUVyNxwOPlpphowwMyhl9E5G7E-fgpArHqtznRujAhUViFKsNa/s1600/mappingdata.jpg" /></a></div>
This is a helper class which contains the meta data (mapping informations) about the entity class.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqzp0iX_MLXYdKQuXg0qm-5BcdPHjLJkIIBKcW7KcPkH1n6eRiEbgd0UaAiFfK-pCOhmN_yhUZGaVLnwftOuZbL83St9Jb0QH_8MkV9v-0roVWlrIwGtoNeJoPymXkzBB8fytZURFIcpAU/s1600/help.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqzp0iX_MLXYdKQuXg0qm-5BcdPHjLJkIIBKcW7KcPkH1n6eRiEbgd0UaAiFfK-pCOhmN_yhUZGaVLnwftOuZbL83St9Jb0QH_8MkV9v-0roVWlrIwGtoNeJoPymXkzBB8fytZURFIcpAU/s1600/help.jpg" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: left;">
This is the most important helper class which is responssible for the antire secret behind ORM. </div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul style="text-align: left;">
<li>Introspects the enity class and stores the meta data(mapping infromations) </li>
<li>Generates the SQL on demand for every operations like insert, update, find, delete using Java Reflection API</li>
</ul>
<b><i><span style="color: #3d85c6;">The entire framework works with Reflection and Annotation API.</span></i></b><br />
<br />
<br />
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. </div>
<br />
<br />
<br />
<br />
<br /></div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-12061118060766164302016-02-26T22:03:00.004-08:002016-03-11T09:38:41.237-08:004 x 4 Sliding Block Puzzle<div dir="ltr" style="text-align: left;" trbidi="on">
Simple steps to have fun :<br />
<div>
<ul style="text-align: left;">
<li><div>
Download the file <a href="https://github.com/PrabhatKJena/SlidingPuzzle" target="_blank"><i>Sliding Block Puzzle</i></a></div>
</li>
<li><div>
Make sure file should be save as <i style="font-weight: bold;">.html </i>file, else rename it to <b><i><filename>.html</i></b></div>
</li>
<li>Open downloaded file in browser </li>
<li>Select any pattern you want to solve from left side then start game</li>
</ul>
<div>
<span style="color: orange;"> </span><span style="color: #cc0000;"> <b><i>Enjoy !!!</i></b></span><br />
<span style="color: #cc0000;"><b><i><br /></i></b></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiDotHjkmiAQR-QHKpjtb4Amdtz2kz1qOnmUAodoZbt2RPqkqrNLugoasctZOclhaJNoOXdEA0LmUGOluQd2tIuaD3ujIOXeswFuz3IOkc04R1odchdooUGrNyINkZB9NjXCd33I2htBZ4/s1600/sc1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiDotHjkmiAQR-QHKpjtb4Amdtz2kz1qOnmUAodoZbt2RPqkqrNLugoasctZOclhaJNoOXdEA0LmUGOluQd2tIuaD3ujIOXeswFuz3IOkc04R1odchdooUGrNyINkZB9NjXCd33I2htBZ4/s1600/sc1.jpg" /></a></div>
<div>
<br /></div>
</div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-74135521920113729962016-02-14T09:40:00.000-08:002016-02-27T22:39:04.776-08:00Spring Data MongoDB Integration<div dir="ltr" style="text-align: left;" trbidi="on">
<b>A brief on MongoDB:</b><br />
<ul style="text-align: left;">
<li>MongoDB is a cross-platform, document oriented database, and leading NoSQL database. </li>
<li>It provides, high performance, high availability, and easy scalability. It works on concept of collection and document.</li>
</ul>
Few terminologies of MongoDB related to RDBMS :<br />
<div>
<ul style="text-align: left;">
<li>Database -- Database</li>
<li>Collection -- Table</li>
<li>Document -- Record</li>
<li>Column -- Field</li>
</ul>
For more on MongoDB, please visit : <a href="https://docs.mongodb.org/manual/tutorial/" target="_blank">MongoDB Tutorials</a></div>
<div>
<br /></div>
<div>
<b>A simple example with MongoDB :</b><br />
<b><i><span style="color: blue;"> Get the source here <a href="https://github.com/PrabhatKJena/SpringDataMongo" target="_blank">https://github.com/PrabhatKJena/SpringDataMongo</a></span></i></b></div>
<div>
<ul style="text-align: left;">
<li>Installation guide : <a href="https://docs.mongodb.org/manual/installation/" target="_blank">Install MongoDB</a> </li>
<li>Libraries : include <span style="background-color: white; font-family: "courier new"; font-size: 9pt;">mongo-java-driver-2.11.0.jar</span><span style="background-color: white; font-family: "courier new";"> </span><span style="background-color: white;"><span style="font-family: inherit;">into class path</span></span></li>
<li><span style="background-color: white;">create database as "booksDB"</span></li>
<li><span style="background-color: white;">create collection as "books"</span></li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKIXDCuoJWMQ0CwQZPBx1UxxWHP3JAM90hNeaDD303zlX_SN7HI0CIr8X7J-0X-YQqJTL7qM9MpzmziQTfdr_JQDaKYC2JJeeWWvAYYuowum2-h_VMOqby8xSLrpw6nM7xf6lMv_Ip47_W/s1600/SC1.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKIXDCuoJWMQ0CwQZPBx1UxxWHP3JAM90hNeaDD303zlX_SN7HI0CIr8X7J-0X-YQqJTL7qM9MpzmziQTfdr_JQDaKYC2JJeeWWvAYYuowum2-h_VMOqby8xSLrpw6nM7xf6lMv_Ip47_W/s1600/SC1.jpg" /></a></div>
<b>Output : </b><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNmdWJNYlqTxSYjPjYOSR_Fm5eQ4V8mU67oLsAZ7vi8iutvTR6vECy_BTzmi92TEx68IKg5-eMt2kpLFmYjxUP8tHH0gZUyDLZ90D0NEfMP37uk3W7L13uZTlhtJ_NjopN_VdAlQeC-_9V/s1600/SC2.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNmdWJNYlqTxSYjPjYOSR_Fm5eQ4V8mU67oLsAZ7vi8iutvTR6vECy_BTzmi92TEx68IKg5-eMt2kpLFmYjxUP8tHH0gZUyDLZ90D0NEfMP37uk3W7L13uZTlhtJ_NjopN_VdAlQeC-_9V/s1600/SC2.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Spring Data Integration with MongoDB:</b></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Here we will see an example using MongoTemplate (same as JdbcTemplate) and Repository.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Defining document class like entity class.</div>
<div class="separator" style="clear: both; text-align: left;">
<i><span style="color: magenta;">Book.java</span></i></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOLQ7pYB4ZH_2-h1GSvbYc-Sqk70EbS3_TbH6Mm1_USVjfDf1usXCFguRUg3ruO5rfVhlSlSTuAGDTP_fQHXF7CC2CZJE7_zVuaKYtjGX3ki7X32YYBXZfVBq2EcaQULo5QpXXecNYZV_8/s1600/sc3.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOLQ7pYB4ZH_2-h1GSvbYc-Sqk70EbS3_TbH6Mm1_USVjfDf1usXCFguRUg3ruO5rfVhlSlSTuAGDTP_fQHXF7CC2CZJE7_zVuaKYtjGX3ki7X32YYBXZfVBq2EcaQULo5QpXXecNYZV_8/s1600/sc3.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Defining annoation based Spring configuration class</div>
<div class="separator" style="clear: both; text-align: left;">
<i><span style="color: magenta;">SpringConfiguration.java</span></i></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT05OkQNfsgZSkOWuezxSQOnq-EAS1HDMRMt0N7jZKUeA_dCM81OWRNd0aFqSiypuLz2LAb86U-prLBTOS81xYj4GB79hEt2uLQdRkcy7OSZ1Ms0uYm5-8AUZzI0g60CBbDCl732o3FNu6/s1600/sc4.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT05OkQNfsgZSkOWuezxSQOnq-EAS1HDMRMt0N7jZKUeA_dCM81OWRNd0aFqSiypuLz2LAb86U-prLBTOS81xYj4GB79hEt2uLQdRkcy7OSZ1Ms0uYm5-8AUZzI0g60CBbDCl732o3FNu6/s1600/sc4.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="color: red;">Note : Add @EnableMongoRepositories to enable all repositories defined</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="color: red;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
Defining repogitory for Book entity</div>
<div class="separator" style="clear: both; text-align: left;">
<i><span style="color: magenta;">BookRepository.java</span></i></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHJRHgVjiT-EMEq1eAe6e6Y9TucvxnY_Mndsv_ohKBpu3wLsVlCntNVn9RG37HtYhAxH8_oR39yj2kN5q26dOYGyTmKPENc-G4zvo-7AMNLtKhlep4bV9Ih2zw628iVggA24ZHqtkinFo_/s1600/sc5.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHJRHgVjiT-EMEq1eAe6e6Y9TucvxnY_Mndsv_ohKBpu3wLsVlCntNVn9RG37HtYhAxH8_oR39yj2kN5q26dOYGyTmKPENc-G4zvo-7AMNLtKhlep4bV9Ih2zw628iVggA24ZHqtkinFo_/s1600/sc5.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Defining test class (main class). This class can be the service class in the real time application.</div>
<div class="separator" style="clear: both; text-align: left;">
<i><span style="color: magenta;">Main.java</span></i></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijWXwMB4qHL0Xgar-zr04ehaz6wOBYcae1prQEqTf_ExysCWhrYg7HpAGrfbbEWgsu4OmJFGbJYuMUS0D2xG81NuoVXnf58gYW-lPlrdl-CJqPzIfUmHiIo2XBb1gCF9XBM65oOHbWJ3fm/s1600/sc6.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijWXwMB4qHL0Xgar-zr04ehaz6wOBYcae1prQEqTf_ExysCWhrYg7HpAGrfbbEWgsu4OmJFGbJYuMUS0D2xG81NuoVXnf58gYW-lPlrdl-CJqPzIfUmHiIo2XBb1gCF9XBM65oOHbWJ3fm/s1600/sc6.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Output:</b></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLY1gKJDBV_YsPJ3fmMmZD8g95akpU85q95PTbrRdRtJi1VMGTRWcP4ceIDtD0B0rH-GzG_7dJz4CXQJjgXpLMw3m5OthtqBa7H4bBMOXvZ3MStKq_s2b5soWljOzf4UD5wbIwy8WhWrl2/s1600/sc7.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLY1gKJDBV_YsPJ3fmMmZD8g95akpU85q95PTbrRdRtJi1VMGTRWcP4ceIDtD0B0rH-GzG_7dJz4CXQJjgXpLMw3m5OthtqBa7H4bBMOXvZ3MStKq_s2b5soWljOzf4UD5wbIwy8WhWrl2/s1600/sc7.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="color: magenta; font-family: "georgia" , "utopia" , "palatino linotype" , "palatino" , serif;"><span style="background-color: white; font-size: 15.3999996185303px; line-height: 21.5599994659424px;"><i>Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. </i></span></span></div>
<br />
<ul style="text-align: left;">
</ul>
</div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-76317714733933018022016-02-13T01:34:00.001-08:002016-02-13T01:42:15.079-08:00Secrets of Double Brace Initialization<div dir="ltr" style="text-align: left;" trbidi="on">
<b>What is Double Brace Initialization (DBI)? </b><br />
Using this feature we can create and initialize an object in a single line.<br />
<b><i>Confused </i></b>? Lets see a simple example : We have a requirement that to initialize all items of a vegetable shop with price.<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLL8lW7_bXENB-vR1BVPGoD2J5oju108KenH4ipFoataAT61-HQMUsV3Gmi5OONxfgsjj0vaLoIjFG9jlLulOMsorMt_aQI3lYFXpBEl5QZ-my5kwEp0LEr1z0FSse0rlg3nzc1ap6pgdu/s1600/Screenshot_1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLL8lW7_bXENB-vR1BVPGoD2J5oju108KenH4ipFoataAT61-HQMUsV3Gmi5OONxfgsjj0vaLoIjFG9jlLulOMsorMt_aQI3lYFXpBEl5QZ-my5kwEp0LEr1z0FSse0rlg3nzc1ap6pgdu/s1600/Screenshot_1.jpg" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: left;">
<b>Output:</b></div>
Items available with Price :<br />
{FRUITS={Apple=120, Grapes=80, Orange=40}, VEGETABLES={Potato=22, Onion=30, Tomato=60}}<br />
<br />
This is how we normally do. And this needs 11 lines of code to create and initialize 3 maps.<br />
<br />
Now We will re-write the same requirement using DBI feature and see how it is handy for developers.<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWgE6cCEhS7LYhqW-W1QqwAAf6GVYF_k9BAynHfW36XPwCpNKOxKobmqdrWCpjmepw3TQlrz8ORwUFFGc9cbUbpeQQPSRfZYCbzeLdpS2nztd8spoBRn40ESaTxQtuZKSp9JCkJgj8zYG8/s1600/Screenshot_2.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWgE6cCEhS7LYhqW-W1QqwAAf6GVYF_k9BAynHfW36XPwCpNKOxKobmqdrWCpjmepw3TQlrz8ORwUFFGc9cbUbpeQQPSRfZYCbzeLdpS2nztd8spoBRn40ESaTxQtuZKSp9JCkJgj8zYG8/s1600/Screenshot_2.jpg" /></a><b>Output: (Same as previous)</b></div>
<div class="separator" style="clear: both;">
Items available with Price : </div>
<div class="separator" style="clear: both;">
</div>
<div class="separator" style="clear: both;">
{FRUITS={Apple=120, Grapes=80, Orange=40}, VEGETABLES={Potato=22, Onion=30, Tomato=60}}</div>
<br />
<b>Now See the Secret behind this :</b><br />
Let see with a simple example with DBI.<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZxyrMVTkjyG23imNKWgzGlwLw0W7iGM7e5TV7MfJRIjPyKB4E0kqnTH-pc56qRNCjFIAHI_qQA_LW8tDCt6Q9k-TA0ACKyp7D9838xGaXtTrw1xucKc03PBu71cdwdQ1VtD0wJBUmq3XS/s1600/Screenshot_3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZxyrMVTkjyG23imNKWgzGlwLw0W7iGM7e5TV7MfJRIjPyKB4E0kqnTH-pc56qRNCjFIAHI_qQA_LW8tDCt6Q9k-TA0ACKyp7D9838xGaXtTrw1xucKc03PBu71cdwdQ1VtD0wJBUmq3XS/s1600/Screenshot_3.jpg" /></a></div>
<b>Output:</b><br />
edu.pk.core.DoubleBraceInitialization2$1<br />
<br />
{Potato=22, Onion=30, Tomato=60}<br />
<br />
We know that while using an anonymous class, compiler creates a separate .class file for the inner class of the enclosing class with the provided overriden method . In similar way, for this DBI feature also compiler creates a separate,class file for the inner class and directly copies the statements written inside {{ and }} and put into the constructor of the inner class.<br />
In output, we can see it prints the class name as <b><i>edu.pk.core.DoubleBraceInitialization2$1</i></b><br />
And the inner class will be look like :<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVYrR9FSNgrYuPKVQ8MtjmaUuKuZ4_BVqlsAbtvBa089umzISKIsq_bMAHHA04DPPb2XujUWQH2wgchlry0IfycDzTphteBSfOiTYij9Y1Cbd7CSBRyl59bidYEgLgF9EZ02Ifkkt7_ur6/s1600/Screenshot_4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVYrR9FSNgrYuPKVQ8MtjmaUuKuZ4_BVqlsAbtvBa089umzISKIsq_bMAHHA04DPPb2XujUWQH2wgchlry0IfycDzTphteBSfOiTYij9Y1Cbd7CSBRyl59bidYEgLgF9EZ02Ifkkt7_ur6/s1600/Screenshot_4.jpg" /></a></div>
Observe here, the compiler just copied all lines written inside {{ and }} and put inside the constructor body.<br />
<br />
So if we understand the secret behind, then now we can sure that we can instantiate and initialize the object our own class using DBI feature provided that class must have non-private constructor which we will use to instantiate the object. <i>Because inheritance is not possible if super class has private construtor.</i><br />
<i><br /></i>
So it is cool, right? But wait a minute..... I want show something.<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1VycqRE9rwmPNQxad28DIlyFei13HZW_ja91Ha8KhYimlxYQQ29iqAam77EWyccUeHv_zBCeqKl0XLxUhaH7t6a2c_zm9bl5XbVkGUHCrHwnWP77C8aOuOaxvuGfKYqnNCwzbnkge1jNz/s1600/Screenshot_5.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1VycqRE9rwmPNQxad28DIlyFei13HZW_ja91Ha8KhYimlxYQQ29iqAam77EWyccUeHv_zBCeqKl0XLxUhaH7t6a2c_zm9bl5XbVkGUHCrHwnWP77C8aOuOaxvuGfKYqnNCwzbnkge1jNz/s1600/Screenshot_5.jpg" /></a></div>
See here how many .class files are created while using DBI, for class <b style="font-style: italic;">DoubleBraceInitialization1.java. </b>1 for main class and 3 for inner classes for the map initialization. So imagine, how many class file it will create if we use such kind of code in our application. For each and every call to the method it will create all these files which is a burden for the class lodaer. Beacuse of this issue, it is not recomendade to use such type of initialization.<br />
<br />
<b><span style="color: red;">Warning:</span></b><br />
<span style="color: red;"><i>Use of this can be lead to performance issue and memory leak problem.</i></span><br />
<span style="color: red;"><i><br /></i></span>
<span style="color: red;"><i><br /></i></span>
<i>Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. </i></div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-7458898415618284112016-02-08T03:08:00.000-08:002016-02-15T03:09:34.552-08:00Secret of java.lang.Threadlocal - Part II<div dir="ltr" style="text-align: left;" trbidi="on">
<b>What is ThreadLocal ?</b><br />
<br />
The ThreadLocal class is provided by Java core API as part of java.lang package. This class is used to maintain the individual local copy for each thread. Even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.<br />
<br />
Let's see an example to understand better.<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZmxOVE3TDn66Iyo75X3Slg2JHi0Y4KahSXw3XwJV60oduwInisMrsvmKbjmOvjIC-nd8fLnED9e395edCuueeO8G07q-45ONF8mMkWJi7NZP05G8HffDTlihjaFEf3L_yWYMHw-APw-dD/s1600/p1.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZmxOVE3TDn66Iyo75X3Slg2JHi0Y4KahSXw3XwJV60oduwInisMrsvmKbjmOvjIC-nd8fLnED9e395edCuueeO8G07q-45ONF8mMkWJi7NZP05G8HffDTlihjaFEf3L_yWYMHw-APw-dD/s1600/p1.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<b>Output:</b><br />
First generated : 101<br />
Second generated : 102<br />
Second generated : 104<br />
Second generated : 105<br />
Second generated : 106<br />
Second generated : 107<br />
First generated : 103<br />
First generated : 108<br />
First generated : 109<br />
First generated : 110<br />
<div>
<br /></div>
<div>
Here we are expecting two generator threads should generate IDs starting from the supplied initial value (100). But observer here in o/p, since the threads are sharing the common variable <i style="font-weight: bold;">currentId, </i>it fails to generate the required IDs as there is only one copy of the variable for all threads. To resolve this issue we have to maintain an individual copy for each thread so that there will not be any conflict among the threads.</div>
<div>
<br /></div>
<div>
Example with our own custom ThreadLocal class (<b><i>MyThreadLocal.java</i></b>)</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhP-B04yCYW3IXBI2NpJepkPiQx57Vf3YwIQ5kjL4HfVnqOGq-G1Ne8FlFL3YvW21hEfDaiZbFVyBJlFz7imcuPaxIUe9VG1tAQwh8TcWxc5qzsd5gaaoRxbTVgWaIjYG6gyrv95O4BuX1h/s1600/p2.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhP-B04yCYW3IXBI2NpJepkPiQx57Vf3YwIQ5kjL4HfVnqOGq-G1Ne8FlFL3YvW21hEfDaiZbFVyBJlFz7imcuPaxIUe9VG1tAQwh8TcWxc5qzsd5gaaoRxbTVgWaIjYG6gyrv95O4BuX1h/s1600/p2.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWOFrmcRDXRPCY1l8LfQJzumDmdy2EamQdYCpIImsa5KyWGwG6Sv2NRDFRrLCmBb3eFQgEfy4TOSNyXr75_BKmiyrGklWZBJ3tPBmGRJTUEdyhX0wLBMDBbP1ekw33CUgVN9xUNiNzGpnv/s1600/p3.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWOFrmcRDXRPCY1l8LfQJzumDmdy2EamQdYCpIImsa5KyWGwG6Sv2NRDFRrLCmBb3eFQgEfy4TOSNyXr75_BKmiyrGklWZBJ3tPBmGRJTUEdyhX0wLBMDBbP1ekw33CUgVN9xUNiNzGpnv/s1600/p3.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSHZyfqy9iLPogPsPAr0WQglzsq70ufvmYZAQ5rBmY3OtVziza_p8IGYiyekVbKow8ih0e6EVJJ0bA9D8SCwbjf9j_0yQNM2cy98PpzF9TxtRFWbu0bPquBUwmRBqPI1bRjRrRSWzjflZ1/s1600/p3.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSHZyfqy9iLPogPsPAr0WQglzsq70ufvmYZAQ5rBmY3OtVziza_p8IGYiyekVbKow8ih0e6EVJJ0bA9D8SCwbjf9j_0yQNM2cy98PpzF9TxtRFWbu0bPquBUwmRBqPI1bRjRrRSWzjflZ1/s1600/p3.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Output:</b></div>
<div class="separator" style="clear: both;">
First generated : 101</div>
<div class="separator" style="clear: both;">
First generated : 102</div>
<div class="separator" style="clear: both;">
First generated : 103</div>
<div class="separator" style="clear: both;">
First generated : 104</div>
<div class="separator" style="clear: both;">
Second generated : 101</div>
<div class="separator" style="clear: both;">
First generated : 105</div>
<div class="separator" style="clear: both;">
Second generated : 102</div>
<div class="separator" style="clear: both;">
Second generated : 103</div>
<div class="separator" style="clear: both;">
Second generated : 104</div>
<div class="separator" style="clear: both;">
</div>
<div class="separator" style="clear: both;">
Second generated : 105</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
Now here each thread is generating the IDs starting from 100 individually with the same common variable <i style="font-weight: bold;">currentId </i>but declared as <b><i>MyThreadLocal. </i></b></div>
<div class="separator" style="clear: both;">
<b><i><br /></i></b></div>
<div class="separator" style="clear: both;">
java.lang.ThreadLocal also works in similar fasion. So instead of creating your own custom ThreadLocal class you can use that class as that having more flexibility and other benefits. This MyThreadLocal class I have written to demonstrate how internally java.lang.Threadlocal class works.</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
Thanking you for visiting this blog. Please feel free to share your comment/suggestion.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div>
<br /></div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-75671843684174393042016-02-02T08:51:00.003-08:002016-02-02T18:08:12.138-08:00Impementing LRU (Least Recent Used) cache is simpler than what you think actually<div dir="ltr" style="text-align: left;" trbidi="on">
<b>What is Cache ? </b><br />
A cache is an area of local memory that holds a copy of frequently accessed data(limited no of data) so future requests for that data can be served faster.<br />
<br />
<b>Next is LRU ? </b><br />
<span style="color: #252525; font-family: sans-serif;"><span style="background-color: white; font-size: 14px; line-height: 22.3999996185303px;">This is the technique which discards the least recently used items from the cache.</span></span><br />
<br />
Implementing LRU cache in Java is as simple as just instantiating java.util.LinkedHashMap.<br />
So before going forward, first of all we need to know the secret of LinkedHashMap<br />
(Refer my previous blog <a href="http://secretsinjava.blogspot.in/2015/11/know-linkedhashmap-in-depth.html">http://secretsinjava.blogspot.in/2015/11/know-linkedhashmap-in-depth.html</a> for more details).<br />
<br />
Now the Secrets :<br />
<span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 12px;">#1.</span> <span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 9pt;"><i><b>accessOrder</b></i> : this is a boolean flag which is passed to LinkedHashMap constructor while instantiating. i.e It keeps the last accessed entry as last of the double linked list which LinkedHashMap used internally.</span><br />
<span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 9pt;"><br /></span>
<span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 9pt;">#2. <i><b>protected boolean removeEldestEntry(Map.Entry<String, String> eldest);</b></i></span><br />
<span style="color: #222222; font-family: "courier new" , "courier" , monospace;"><span style="font-size: 12px;">This is the method of <b><i>LinkHashMap</i> </b>which decides whether the map should remove its eldest entry or not. For each eldest entry, this method is invoked by <b><i>put()</i></b> and <b><i>putAll()</i></b> method after inserting a new entry into the map. </span></span><span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 12px;">Default this method returns <b><i>false</i></b> to keep all entries added into the map. This method can be overriden by the implentor to decide the no of entries can be kept in the map.</span><br />
<span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 12px;"><br /></span>
<span style="color: #222222; font-family: "courier new" , "courier" , monospace; font-size: 12px;">Example : </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOdKp0En2vkMu10k8lSuLoUH5MF0yF-6P4nrU1r3FWB4hfc0caeDwlrcYURBbkO5qqfduzce-1y2rF1O3LJHcRCCjdkdyBa_0nJ6fP-pqzCZrNtiibr8-h0JDPvuOpPDa1ex5HUMfN5tJ3/s1600/LHM_1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOdKp0En2vkMu10k8lSuLoUH5MF0yF-6P4nrU1r3FWB4hfc0caeDwlrcYURBbkO5qqfduzce-1y2rF1O3LJHcRCCjdkdyBa_0nJ6fP-pqzCZrNtiibr8-h0JDPvuOpPDa1ex5HUMfN5tJ3/s1600/LHM_1.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Output :</div>
<div class="separator" style="clear: both;">
{A4=2552, A5=2444}</div>
<div>
<br /></div>
<div>
Here the overriden method retuns <i><b>true</b></i> if size is more than 2. So the map always deletes the oldest entry when a new etry is put into it.</div>
<div>
<br /></div>
<div>
Now we understood the secrets of <i><b>LinkedHashMap</b></i>. So now implementing the <b><i>LRU cache</i></b> is just creating a <i><b>LinkedHashMap </b></i>provided above 2 proprties.</div>
<div>
Example :</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEphBuYSMubQ_czYMO6aPaU83OEBVnZioWuLeMH0M16kxovumjU3IEiuKB1pgsXyOj78YIrx1tWxAJ73LQMB1NwRgxkM3j_6Com96gcXj-qf3sQ9PhtK4bmbx3s4LXVXb2DojqXsoK1HSy/s1600/LRU_2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEphBuYSMubQ_czYMO6aPaU83OEBVnZioWuLeMH0M16kxovumjU3IEiuKB1pgsXyOj78YIrx1tWxAJ73LQMB1NwRgxkM3j_6Com96gcXj-qf3sQ9PhtK4bmbx3s4LXVXb2DojqXsoK1HSy/s1600/LRU_2.jpg" /></a></div>
<div>
<br /></div>
<div>
Output : </div>
<div>
{A6=Theta6, A1=Theta345, A3=Theta11, A2=Theta234}</div>
<div>
<br /></div>
<div>
Here we have given CACHE_SIZE = 4. So the map deletes all eldest entry when size > 4. The final content of the map the last 4 accessed keys.</div>
<div>
<br /></div>
<div>
Thats all about the LRU implementation using java.util.LinkdHashMap. In place of LinkedHashMap you can also implement your own Map and using double linked internally. </div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Please feel free to give your comment/suggestion. Thank you.</div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-53350605687887195852015-11-26T02:20:00.001-08:002015-11-26T02:24:29.355-08:00Why Key of a Map must be Immutable ?<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Immutable Object :</b><br />
An immutable object is a special kind of object whose state can not be changed once it is created. These objects are used in concurrent applications as the states can not be changed, So there is no question of corrupting the state by thread interference. And one more major use is while working with <b>java.util.Map</b> the key must be an immutable object. Else once you have added one entry to the map and after that if the state of the key got changed then you will lose the object mapping.<br />
<br />
Example:<br />
<span style="color: navy; font-family: "courier new"; font-size: 9pt; font-weight: bold;">class </span><span style="background-color: white; font-family: "courier new"; font-size: 9pt;">User {</span><br />
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"> String <span style="color: #660e7a; font-weight: bold;">email</span>;
String <span style="color: #660e7a; font-weight: bold;">name</span>;
<span style="color: navy; font-weight: bold;">public </span>User(String email, String name) {
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">email </span>= email;
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">name </span>= name;
}
<span style="color: navy; font-weight: bold;">public </span>String getEmail() {
<span style="color: navy; font-weight: bold;">return </span><span style="color: #660e7a; font-weight: bold;">email</span>;
}
<span style="color: navy; font-weight: bold;">public void </span>setEmail(String email) {
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">email </span>= email;
}
<span style="color: navy; font-weight: bold;">public </span>String getName() {
<span style="color: navy; font-weight: bold;">return </span><span style="color: #660e7a; font-weight: bold;">name</span>;
}
<span style="color: navy; font-weight: bold;">public void </span>setName(String name) {
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">name </span>= name;
}
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">public boolean </span>equals(Object o) {
<span style="color: navy; font-weight: bold;">if </span>(<span style="color: navy; font-weight: bold;">this </span>== o) <span style="color: navy; font-weight: bold;">return true</span>;
<span style="color: navy; font-weight: bold;">if </span>(o == <span style="color: navy; font-weight: bold;">null </span>|| getClass() != o.getClass()) <span style="color: navy; font-weight: bold;">return false</span>;
User user = (User) o;
<span style="color: navy; font-weight: bold;">if </span>(!<span style="color: #660e7a; font-weight: bold;">email</span>.equals(user.<span style="color: #660e7a; font-weight: bold;">email</span>)) <span style="color: navy; font-weight: bold;">return false</span>;
<span style="color: navy; font-weight: bold;">return </span><span style="color: #660e7a; font-weight: bold;">name</span>.equals(user.<span style="color: #660e7a; font-weight: bold;">name</span>);
}
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">public int </span>hashCode() {
<span style="color: navy; font-weight: bold;">int </span>result = <span style="color: #660e7a; font-weight: bold;">email</span>.hashCode();
result = <span style="color: blue;">31 </span>* result + <span style="color: #660e7a; font-weight: bold;">name</span>.hashCode();
<span style="color: navy; font-weight: bold;">return </span>result;
}
}</pre>
<pre style="background-color: white;"><pre style="font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;">public class </span>ImmutableKeyTest {
<span style="color: navy; font-weight: bold;">public static void </span>main(String[] args) {
Map<User, String> userDealMap = <span style="color: navy; font-weight: bold;">new </span>HashMap<>();
User user = <span style="color: navy; font-weight: bold;">new </span>User(<span style="color: green; font-weight: bold;">"abc@gmail.com"</span>, <span style="color: green; font-weight: bold;">"ABC"</span>);
User user1 = <span style="color: navy; font-weight: bold;">new </span>User(<span style="color: green; font-weight: bold;">"xyz@gmail.com"</span>, <span style="color: green; font-weight: bold;">"XYZ"</span>);
userDealMap.put(user, <span style="color: green; font-weight: bold;">"HAPPY50"</span>);
userDealMap.put(user1, <span style="color: green; font-weight: bold;">"HAPPY25"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(userDealMap);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"Before Key Change"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(userDealMap.get(user));
user.setName(<span style="color: green; font-weight: bold;">"ABC DEF"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"After Key Change"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(userDealMap.get(user));
}
}</pre>
<b>Output:</b>
<span style="font-family: "courier new";"><span style="font-size: 12px;">{User@b42dca6f=HAPPY25, User@4a84e2cf=HAPPY50}
Before Key Change
HAPPY50
After Key Change
null</span></span>
<span style="font-family: "courier new";"><span style="font-size: 12px;">
Here when the name of the user got changed, it impacts the hashCode of the user object, so while getting the value from the map, it treats the supplied key as a new key and returns NULL.</span></span>
</pre>
<span style="font-family: "courier new";"><span style="font-size: 12px;"><b><br /></b></span></span>
<span style="font-family: "courier new";"><span style="font-size: 12px;"><b>Solution:</b></span></span>
<span style="font-family: "courier new";"><span style="font-size: 12px;">Solution is very simple ! Make the User object as immutable object.</span></span>
<span style="font-family: "courier new";"><span style="font-size: 12px;">(Guideline for creating immutable object refer <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html">https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html</a></span></span><span style="font-family: "courier new"; font-size: 12px;">)</span>
<br />
<span style="font-family: "courier new"; font-size: 12px;"></span><br />
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;">final class </span>User {
<span style="color: navy; font-weight: bold;">final </span>String <span style="color: #660e7a; font-weight: bold;">email</span>;
<span style="color: navy; font-weight: bold;">final </span>String <span style="color: #660e7a; font-weight: bold;">name</span>;
<span style="color: navy; font-weight: bold;">public </span>User(String email, String name) {
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">email </span>= email;
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">name </span>= name;
}
<span style="color: navy; font-weight: bold;">public </span>String getEmail() {
<span style="color: navy; font-weight: bold;">return </span><span style="color: #660e7a; font-weight: bold;">email</span>;
}
<span style="color: navy; font-weight: bold;">public </span>String getName() {
<span style="color: navy; font-weight: bold;">return </span><span style="color: #660e7a; font-weight: bold;">name</span>;
}
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">public boolean </span>equals(Object o) {
<span style="color: navy; font-weight: bold;">if </span>(<span style="color: navy; font-weight: bold;">this </span>== o) <span style="color: navy; font-weight: bold;">return true</span>;
<span style="color: navy; font-weight: bold;">if </span>(o == <span style="color: navy; font-weight: bold;">null </span>|| getClass() != o.getClass()) <span style="color: navy; font-weight: bold;">return false</span>;
User user = (User) o;
<span style="color: navy; font-weight: bold;">if </span>(!<span style="color: #660e7a; font-weight: bold;">email</span>.equals(user.<span style="color: #660e7a; font-weight: bold;">email</span>)) <span style="color: navy; font-weight: bold;">return false</span>;
<span style="color: navy; font-weight: bold;">return </span><span style="color: #660e7a; font-weight: bold;">name</span>.equals(user.<span style="color: #660e7a; font-weight: bold;">name</span>);
}
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">public int </span>hashCode() {
<span style="color: navy; font-weight: bold;">int </span>result = <span style="color: #660e7a; font-weight: bold;">email</span>.hashCode();
result = <span style="color: blue;">31 </span>* result + <span style="color: #660e7a; font-weight: bold;">name</span>.hashCode();
<span style="color: navy; font-weight: bold;">return </span>result;
}
}</pre>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;">Once you make it immutable, you can not change the state of the object by any chance.</pre>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"><pre style="font-family: 'Courier New'; font-size: 9pt;"><span style="color: grey; font-style: italic;">// user.setName("ABC DEF"); // This will give compilation error as no setter method there</span></pre>
<pre style="font-family: 'Courier New'; font-size: 9pt;"><span style="color: grey; font-style: italic;">
</span></pre>
</pre>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-74752627975820996142015-11-24T00:14:00.000-08:002015-11-24T00:14:33.486-08:00Know LinkedHashMap in Depth<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: "courier new" , "courier" , monospace;"><b>LinkedHashMap </b>is a map which extends <b>HashMap</b> class and implements <b>Map </b>interface. But the only different between LinkedHashMap and HashMap is LinkedHashMap maintains the insertion order whereas HashMap doesn't. LinkedHashMap uses double LinkedList internally to maintain the order.</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"><span style="font-family: "courier new" , "courier" , monospace;"><br /></span>
<span style="font-family: "courier new" , "courier" , monospace;">Example :</span></span><br />
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"><span style="font-family: "courier new" , "courier" , monospace;"><span style="color: navy; font-weight: bold;">class </span>Employee{
String <span style="color: #660e7a; font-weight: bold;">id</span>;
String <span style="color: #660e7a; font-weight: bold;">name</span>;
<span style="color: navy; font-weight: bold;">public </span>Employee(String id, String name) {
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">id </span>= id;
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">name </span>= name;
}
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">public </span>String toString() {
<span style="color: navy; font-weight: bold;">return </span><span style="color: green; font-weight: bold;">"["</span>+<span style="color: #660e7a; font-weight: bold;">id</span>+<span style="color: green; font-weight: bold;">","</span>+<span style="color: #660e7a; font-weight: bold;">name</span>+<span style="color: green; font-weight: bold;">"]"</span>;
}
}</span></pre>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"></pre>
<pre style="background-color: white;"><pre style="font-family: 'Courier New'; font-size: 9pt;"><span style="font-family: "courier new" , "courier" , monospace; font-size: 9pt;"><span style="color: navy; font-weight: bold;">import </span>java.util.HashMap;
<span style="color: navy; font-weight: bold;">import </span>java.util.LinkedHashMap;
<span style="color: navy; font-weight: bold;">public class </span>LinkedHashMapDemo1 {
<span style="color: navy; font-weight: bold;">public static void </span>main(String[] args) {
LinkedHashMap<Employee, Integer> linkedMap = <span style="color: navy; font-weight: bold;">new </span>LinkedHashMap<>();
HashMap<Employee, Integer> hashMap = <span style="color: navy; font-weight: bold;">new </span>HashMap<>();
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"LinkedHashMap : "</span>);
linkedMap.put(<span style="color: navy; font-weight: bold;">new </span>Employee(<span style="color: green; font-weight: bold;">"1001"</span>,<span style="color: green; font-weight: bold;">"Alpha"</span>), <span style="color: blue;">2000</span>);
linkedMap.put(<span style="color: navy; font-weight: bold;">new </span>Employee(<span style="color: green; font-weight: bold;">"1002"</span>,<span style="color: green; font-weight: bold;">"Beta"</span>), <span style="color: blue;">2000</span>);
linkedMap.put(<span style="color: navy; font-weight: bold;">new </span>Employee(<span style="color: green; font-weight: bold;">"1003"</span>,<span style="color: green; font-weight: bold;">"Gama"</span>), <span style="color: blue;">2000</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(linkedMap);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"HashMap : "</span>);
hashMap.put(<span style="color: navy; font-weight: bold;">new </span>Employee(<span style="color: green; font-weight: bold;">"1001"</span>,<span style="color: green; font-weight: bold;">"Alpha"</span>), <span style="color: blue;">2000</span>);
hashMap.put(<span style="color: navy; font-weight: bold;">new </span>Employee(<span style="color: green; font-weight: bold;">"1002"</span>,<span style="color: green; font-weight: bold;">"Beta"</span>), <span style="color: blue;">2000</span>);
hashMap.put(<span style="color: navy; font-weight: bold;">new </span>Employee(<span style="color: green; font-weight: bold;">"1003"</span>,<span style="color: green; font-weight: bold;">"Gama"</span>), <span style="color: blue;">2000</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(hashMap);
}
}
<b>Output:</b>
<span style="font-family: "courier new" , "courier" , monospace;"><span style="font-family: "courier new";"><span style="font-size: 12px;">LinkedHashMap :
{[1001,Alpha]=2000, [1002,Beta]=2000, [1003,Gama]=2000}
HashMap :
{[1001,Alpha]=2000, [1003,Gama]=2000, [1002,Beta]=2000}</span></span>
</span>
<span style="font-family: "courier new" , "courier" , monospace;"><i>Here LinekedHashMap keeps the insertion order but HashMap doesn't</i>.</span>
<h2 style="text-align: left;">
<b><span style="font-family: "courier new" , "courier" , monospace; font-size: large;">Now the Secret of LinkedHashMap :</span></b></h2>
<span style="font-family: "courier new" , "courier" , monospace;"><span style="font-family: "courier new" , "courier" , monospace;">LinkedHashMap provided a special constructor to maintain access order instead insertion order.</span>
<span style="color: navy; font-weight: bold;">public </span>LinkedHashMap(<span style="color: navy; font-weight: bold;">int </span>initialCapacity, <span style="color: navy; font-weight: bold;">float </span>loadFactor, <span style="color: navy; font-weight: bold;">boolean </span>accessOrder)</span><span style="font-size: 9pt;">
Access Order is like maintaining the order of the entries accessed. </span><i style="font-size: 9pt;"><span style="color: blue;">Access Order is affected by <b>get(key)</b>, <b>put(key,val) </b>and <b>putAll(Map)</b></span></i><span style="font-size: 9pt;">.
Because of this nature, LinkedHashMap is used in </span><b style="font-size: 9pt;">LRU(Least Recent Used) Caching</b><span style="font-size: 9pt;">.</span></span></pre>
</pre>
</div>
<span style="font-family: "courier new" , "courier" , monospace;">Example: </span><br />
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;">import </span>java.util.<span style="background-color: #e4e4ff;">LinkedHashMap</span>;
<span style="color: navy; font-weight: bold;">import </span>java.util.Map;
<span style="color: navy; font-weight: bold;">public class </span>LinkedHashMapTest {
<span style="color: navy; font-weight: bold;">public static void </span>main(String[] args) {
<span style="background-color: #e4e4ff;">LinkedHashMap</span><String, Integer> linkedMap = <span style="color: navy; font-weight: bold;">new </span><span style="background-color: #e4e4ff;">LinkedHashMap</span><>();
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"Default LinkedHashMap : "</span>);
linkedMap.put(<span style="color: green; font-weight: bold;">"Gama"</span>, <span style="color: blue;">2000</span>);
linkedMap.put(<span style="color: green; font-weight: bold;">"Alpha"</span>, <span style="color: blue;">2000</span>);
linkedMap.put(<span style="color: green; font-weight: bold;">"Beta"</span>, <span style="color: blue;">2000</span>);
<span style="color: grey; font-style: italic;">// Once Added after that no change in order</span>
<span style="color: grey; font-style: italic;"> </span>linkedMap.put(<span style="color: green; font-weight: bold;">"Alpha"</span>, <span style="color: blue;">3000</span>);
linkedMap.put(<span style="color: green; font-weight: bold;">"Beta"</span>, <span style="color: blue;">3000</span>);
linkedMap.put(<span style="color: green; font-weight: bold;">"Gama"</span>, <span style="color: blue;">3000</span>);
linkedMap.get(<span style="color: green; font-weight: bold;">"Alpha"</span>);
linkedMap.get(<span style="color: green; font-weight: bold;">"Beta"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(linkedMap);
<span style="color: grey; font-style: italic;">// LinkedHashMap with accessOrder</span><span style="color: grey; font-style: italic;"> </span>
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"LinkedHashMap with accessOrder = TRUE: "</span>);
<span style="background-color: #e4e4ff;">LinkedHashMap</span><String, Integer> linkedAccessedOrderMap = </pre>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;"> new </span><span style="background-color: #e4e4ff;">LinkedHashMap</span><>(<span style="color: blue;">10</span>, <span style="color: blue;">0.5f</span>, <span style="color: navy; font-weight: bold;">true</span>);
linkedAccessedOrderMap.put(<span style="color: green; font-weight: bold;">"Gama"</span>, <span style="color: blue;">2000</span>);
linkedAccessedOrderMap.put(<span style="color: green; font-weight: bold;">"Alpha"</span>, <span style="color: blue;">2000</span>);
linkedAccessedOrderMap.put(<span style="color: green; font-weight: bold;">"Beta"</span>, <span style="color: blue;">2000</span>);
linkedAccessedOrderMap.put(<span style="color: green; font-weight: bold;">"Alpha"</span>, <span style="color: blue;">3000</span>);
linkedAccessedOrderMap.get(<span style="color: green; font-weight: bold;">"Gama"</span>);
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(linkedAccessedOrderMap);
}
}</pre>
<pre style="background-color: white;"><b style="font-family: 'Courier New', Courier, monospace;">Output:</b><span style="font-family: "courier new" , "courier" , monospace;">
</span><span style="font-family: "courier new";"><span style="font-size: 12px;">Default LinkedHashMap :
{Gama=3000, Alpha=3000, Beta=3000}
LinkedHashMap with accessOrder = TRUE:
{Beta=2000, Alpha=3000, Gama=2000}</span></span>
</pre>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-42607258356882403972015-11-23T00:46:00.000-08:002016-02-15T03:09:20.962-08:00Secrets of java.lang.ThreadLocal - Part I<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: "courier new" , "courier" , monospace;"><b><i>java.lang.ThreadLocal</i></b> is given by Java API to achieve the thread-safety in multi-threaded environment. Unlike of synchronization or locking this eliminates the sharing concept rather maintains an individual copy of object for each thread. So no need of locking or synchronization which results more scalability and performance.</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhg5QCfCzjlQzZG7jhSgbkJqDPLdHweavVmSTeKr4wXoHUh-jS2MIZiLwf82GyTSpg4DvytBxve0Xac73wDh3Np5Nd4DwbI7BPximEuQgyHpUW5tINfKGbFKmr0XnhDopOades_9oUGlV1m/s1600/SC1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhg5QCfCzjlQzZG7jhSgbkJqDPLdHweavVmSTeKr4wXoHUh-jS2MIZiLwf82GyTSpg4DvytBxve0Xac73wDh3Np5Nd4DwbI7BPximEuQgyHpUW5tINfKGbFKmr0XnhDopOades_9oUGlV1m/s1600/SC1.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<b><span style="font-family: "courier new" , "courier" , monospace;">Output:</span></b></div>
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYjvAis-pSm7nim7NFbSbH91j515uT_PaSbjAMRrDVvjPlcwdiTIUIuUfgC69xwNUxYlcs7KlS9wt2vMtwulYKtMoNDRCtCq1UphZt5HvsTuGBiyvOjPBVpAGlBlvSR2QqaIC0s91ceAgY/s1600/SC2.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYjvAis-pSm7nim7NFbSbH91j515uT_PaSbjAMRrDVvjPlcwdiTIUIuUfgC69xwNUxYlcs7KlS9wt2vMtwulYKtMoNDRCtCq1UphZt5HvsTuGBiyvOjPBVpAGlBlvSR2QqaIC0s91ceAgY/s1600/SC2.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;">Here <b><i>id </i></b>and <i style="font-weight: bold;">threadLocal </i>both are shared resources but ThreadLocal maintains individual copy for each thread.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace; font-size: large;"><b>Now the Secret of ThreadLocal is</b></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;">- Each Thread object contains an instance member variable as <i><span style="color: blue;">ThreadLocal.ThreadLocalMap threadLocals;</span></i></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;">- Where as <span style="color: blue;"><i>ThreadLocal.ThreadLocalMap</i></span> contains array of entries of <i><span style="color: blue;">java.lang.ref.Reference</span></i> type as <i><span style="color: blue;">private Entry[] table</span></i>;</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;">And this Entry is a simple <key, value> pair like <i>Map.Entry</i> which contains <i><span style="color: blue;">ThreadLocal<?></span></i> as key and <i><span style="color: blue;">Object</span></i> as value</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;">- ThreadLoacl class has 2 important methods </span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>* <i><span style="color: blue;">public void set(T value)</span></i> : while setting the value, it first gets the ThreadLocalMap of the current thread. Then adds an entry with <this ThreadLocal object, passed Value></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>*<span style="color: blue;"> <i>public T get(</i>)</span> : while getting the value, first gets the <i><span style="color: blue;">ThreadLocalMap</span></i> of the current thread. Then get the value for the Entry by passing key as this current ThreadLocal object. If not found any value then sets and returns the initial value provided by the programmer. </span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>[ <span style="color: blue;">ThreadLocal</span> class having a callback method to provide the initial value as <i><span style="color: blue;">protected T initialValue();</span></i> ]</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;">To provide initial value we can override callback method as below :</span></div>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;">ThreadLocal<Integer> <span style="color: #660e7a; font-weight: bold;">threadLocal </span>= <span style="color: navy; font-weight: bold;">new </span>ThreadLocal<Integer>() {
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">protected </span>Integer initialValue() {
<span style="color: navy; font-weight: bold;">return </span><span style="color: blue;">100</span>;
}
};</pre>
<br />
<div class="separator" style="clear: both; text-align: left;">
</div>
<br />
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span>
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span>
<br />
<div style="text-align: left;">
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span></div>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-78470194176311263942015-11-22T23:44:00.000-08:002015-11-22T23:44:04.097-08:00Use Non-final variable inside Anonymous Inner Class<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Courier New, Courier, monospace;">Accessing local variable inside an inner class need to be declared as <i><b>final or effectively final</b></i>(this is new in Java 8). </span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">But if we have a requirement of changing that variable after inner class then we can't declare the local variable as final. So to use that non-final local variable effectively inside inner class we can pass that variable as constructor argument to that inner class and use it.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Example : </span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;">class </span>IdGenerator {
<span style="color: navy; font-weight: bold;">long </span><span style="color: #660e7a; font-weight: bold;">id </span>= <span style="color: blue;">99990000</span>;
<span style="color: navy; font-weight: bold;">public </span>IdGenerator() {
}
<span style="color: navy; font-weight: bold;">public </span>String generateId() {
<span style="color: navy; font-weight: bold;">return </span>String.<span style="font-style: italic;">valueOf</span>(++<span style="color: #660e7a; font-weight: bold;">id</span>);
}
}</pre>
<pre style="background-color: white; font-family: 'Courier New'; font-size: 9pt;">
</pre>
<pre style="background-color: white;"><pre style="font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;">interface </span>Service {
<span style="color: navy; font-weight: bold;">void </span>logData();
}</pre>
<pre style="font-family: 'Courier New'; font-size: 9pt;"><span style="color: navy; font-weight: bold;">public class </span>InnerClassWithNonFinalVariable {
<span style="color: navy; font-weight: bold;">public static void </span>main(String[] args) {
IdGenerator idGenerator = <span style="color: navy; font-weight: bold;">new </span>IdGenerator();
<span style="color: navy; font-weight: bold;">class </span>MyService <span style="color: navy; font-weight: bold;">implements </span>Service {
<span style="color: navy; font-weight: bold;">private </span>IdGenerator <span style="color: #660e7a; font-weight: bold;">generator</span>;
MyService(IdGenerator generator) {
<span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">generator </span>= generator;
}
<span style="color: olive;">@Override</span><span style="color: olive;"> </span><span style="color: navy; font-weight: bold;">public void </span>logData() {
System.<span style="color: #660e7a; font-style: italic; font-weight: bold;">out</span>.println(<span style="color: green; font-weight: bold;">"Logging Data :" </span>+ <span style="color: navy; font-weight: bold;">this</span>.<span style="color: #660e7a; font-weight: bold;">generator</span>.generateId());
}
}
Service service = <span style="color: navy; font-weight: bold;">new </span>MyService(idGenerator);
service.logData();
<span style="color: grey; font-style: italic;">/* Using idGenerator for some other purpose */</span><span style="color: grey; font-style: italic;"> </span>idGenerator = <span style="color: navy; font-weight: bold;">null</span>;
}
}</pre>
<pre style="font-size: 9pt;">
</pre>
<pre>B<span style="font-family: Courier New, Courier, monospace;">ut while working with <i><b>Anonymous Inner Class</b></i>, We don't have option to define constructor. So below demonstrated code shows how to use non-final </span><span style="font-family: 'Courier New', Courier, monospace;">local </span><span style="font-family: 'Courier New', Courier, monospace;">variable inside anonymous inner class.</span></pre>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPARoUHSswe4ki0npZcZbXEZYWI_LWVrSgMEnaC-mo4WcXJPgk7X7B-zDaNlFnmZm6c8X7UFf2_Md0jjeEuVDBHVFYiS0rNRMOsGodtyQnQhTSX2KNak6jsA7czRBfoKIxXKmkCn3yQPi5/s1600/SC.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPARoUHSswe4ki0npZcZbXEZYWI_LWVrSgMEnaC-mo4WcXJPgk7X7B-zDaNlFnmZm6c8X7UFf2_Md0jjeEuVDBHVFYiS0rNRMOsGodtyQnQhTSX2KNak6jsA7czRBfoKIxXKmkCn3yQPi5/s1600/SC.jpg" /></a></div>
<pre><span style="font-family: 'Courier New', Courier, monospace;">
</span></pre>
<pre><span style="font-family: 'Courier New', Courier, monospace;">
</span></pre>
<pre style="font-family: 'Courier New'; font-size: 9pt;">
</pre>
</pre>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0tag:blogger.com,1999:blog-6253472251172770602.post-20329546646890167152015-11-07T08:25:00.000-08:002015-11-07T08:29:35.878-08:00Use Varargs Carefully !<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
<div class="MsoNormal">
<span style="font-family: 'times new roman', serif; font-size: large;">So,
what are the things need to take care while using varargs in Java ?</span></div>
<div class="MsoNormal" style="margin-bottom: 0.0001pt;">
<span style="font-family: "times new roman" , serif; font-size: 13.5pt; font-weight: normal;">Let's take a simple
example : </span></div>
<div class="MsoNormal" style="margin-bottom: 0.0001pt;">
<b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">public static int </span></b><span style="background: white; font-family: "courier new"; font-size: 9pt;">findMax(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int</span></b><span style="background: white; font-family: "courier new"; font-size: 9pt;">... numbers) {</span><span style="font-family: "times new roman" , serif; font-size: 13.5pt;"><o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;"> </span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int
</span></b><span style="font-family: "courier new"; font-size: 9pt;">max = numbers[</span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">0</span><span style="font-family: "courier new"; font-size: 9pt;">];<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">for </span></b><span style="font-family: "courier new"; font-size: 9pt;">(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int </span></b><span style="font-family: "courier new"; font-size: 9pt;">i = </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">1</span><span style="font-family: "courier new"; font-size: 9pt;">; i < numbers.</span><b><span style="color: #660e7a; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">length</span></b><span style="font-family: "courier new"; font-size: 9pt;">; i++) {<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">if </span></b><span style="font-family: "courier new"; font-size: 9pt;">(numbers[i] > max)<br />
max = numbers[i];<br />
}<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">return </span></b><span style="font-family: "courier new"; font-size: 9pt;">max;<br />
}<o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">(</span><span style="color: blue; font-family: "courier new"; font-size: 9pt;">1</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9pt;">2</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9pt;">3</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9pt;">4</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9pt;">5</span><span style="font-family: "courier new"; font-size: 9pt;">); // 5</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">(</span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">10</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">2</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">30</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">4</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">50</span><span style="font-family: "courier new"; font-size: 9pt;">, </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">6</span><span style="font-family: "courier new"; font-size: 9pt;">); // 50<o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">(</span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">3</span><span style="font-family: "courier new"; font-size: 9pt;">); // 3<o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;"><br /></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">Here this above code
looks good and the </span><i style="font-family: 'Courier New'; font-size: 9pt;">findMax() </i><span style="font-family: "courier new"; font-size: 9pt;">method works fine. But the problem here is
in run time it will fail with specific inputs like :</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">null</span></b><span style="font-family: "courier new"; font-size: 9pt;">); // Exception in thread "main"
java.lang.NullPointerException</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">(); // Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0</span><span style="font-family: "courier new"; font-size: 10pt;"><o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;"><br /></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">Because here the code
expects at least one value.</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">So to avoid these
problems we can modify the method in such way like :</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">public static int </span></b><span style="font-family: "courier new"; font-size: 9pt;">findMax(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int</span></b><span style="font-family: "courier new"; font-size: 9pt;">... numbers) {</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;"> </span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">if
</span></b><span style="font-family: "courier new"; font-size: 9pt;">(numbers == </span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">null </span></b><span style="font-family: "courier new"; font-size: 9pt;">|| numbers.</span><b><span style="color: #660e7a; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">length </span></b><span style="font-family: "courier new"; font-size: 9pt;">== </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">0</span><span style="font-family: "courier new"; font-size: 9pt;">)<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">throw new </span></b><span style="font-family: "courier new"; font-size: 9pt;">IllegalArgumentException(</span><b><span style="color: green; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">"At least one input required."</span></b><span style="font-family: "courier new"; font-size: 9pt;">);<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int </span></b><span style="font-family: "courier new"; font-size: 9pt;">max = numbers[</span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">0</span><span style="font-family: "courier new"; font-size: 9pt;">];<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">for </span></b><span style="font-family: "courier new"; font-size: 9pt;">(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int </span></b><span style="font-family: "courier new"; font-size: 9pt;">i = </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">1</span><span style="font-family: "courier new"; font-size: 9pt;">; i < numbers.</span><b><span style="color: #660e7a; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">length</span></b><span style="font-family: "courier new"; font-size: 9pt;">; i++) {<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">if </span></b><span style="font-family: "courier new"; font-size: 9pt;">(numbers[i] > max)<br />
max = numbers[i];<br />
}<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">return </span></b><span style="font-family: "courier new"; font-size: 9pt;">max;<br />
}<o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;"><br /></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">But here we need extra
code:<o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">#1. one more validation
required<o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">#2. the calling method
need to be more cautious to handle <i>"IllegalArgumentException"</i><o:p></o:p></span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<span style="font-family: "courier new"; font-size: 9pt;">Instead of all above
resolution we can handle this problem in a shorter and smarter way by using the
varargs in proper way.</span></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";"><br /></span></b></div>
<div class="MsoNormal" style="background: white; margin-bottom: 0.0001pt;">
<b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">public static int </span></b><span style="font-family: "courier new"; font-size: 9pt;">findMax(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int </span></b><span style="font-family: "courier new"; font-size: 9pt;">firtNumber, </span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int</span></b><span style="font-family: "courier new"; font-size: 9pt;">... numbers) {<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int </span></b><span style="font-family: "courier new"; font-size: 9pt;">max = firtNumber;<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">for </span></b><span style="font-family: "courier new"; font-size: 9pt;">(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">int </span></b><span style="font-family: "courier new"; font-size: 9pt;">i = </span><span style="color: blue; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">0</span><span style="font-family: "courier new"; font-size: 9pt;">; i < numbers.</span><b><span style="color: #660e7a; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">length</span></b><span style="font-family: "courier new"; font-size: 9pt;">; i++) {<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">if </span></b><span style="font-family: "courier new"; font-size: 9pt;">(numbers[i] > max)<br />
max = numbers[i];<br />
}<br />
</span><b><span style="color: navy; font-family: "courier new"; font-size: 9.0pt; mso-fareast-font-family: "Times New Roman";">return
</span></b><span style="font-family: "courier new"; font-size: 9pt;">max;<br />
}<o:p></o:p></span></div>
<div class="MsoNormal">
</div>
<div class="MsoNormal">
<span style="background-color: white; font-family: "courier new"; font-size: 12px;">Here we have made the first number as a separate parameter, So the compiler will not allow to invoke method by passing null or empty arguments like </span><i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">(</span><b><span style="color: navy; font-family: "courier new"; font-size: 9pt;">null</span></b><span style="font-family: "courier new"; font-size: 9pt;">) and </span><i><span style="font-family: "courier new"; font-size: 9pt;">findMax</span></i><span style="font-family: "courier new"; font-size: 9pt;">().</span></div>
<div class="MsoNormal">
<span style="background-color: white; font-family: "courier new"; font-size: 12px;"><br /></span></div>
</h2>
</div>
Prabhathttp://www.blogger.com/profile/06770410018489092466noreply@blogger.com0