tag:blogger.com,1999:blog-58556895097476256962024-03-18T15:18:03.798+05:30Java-LatteJust Java!Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.comBlogger139125tag:blogger.com,1999:blog-5855689509747625696.post-54385544777245192472015-08-09T20:02:00.001+05:302015-08-09T20:02:56.407+05:30File Locking in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">NIO supports file locking to synchronize access to a file. You have the ability to <span style="color: blue;">lock a region</span> of a file or <span style="color: blue;">the entire file</span>. The file locking mechanism is handled by the <span style="color: blue;">operating system</span> and therefore its <span style="color: blue;">exact effect is platform-dependent</span>. On some operating systems, a file lock is advisory, whereas on some, it is mandatory. Since it is handled by the operating system, its effect is visible to other programs as well as to Java programs running in other JVMs. In this article, we try to understand this concept with the help of an example.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-bzgLr91AWcU/VcdkYwrzGYI/AAAAAAAAJzc/F29uQTUzGdY/s1600/How%2Bto%2Block%2Bfiles%2Band%2Bfolder%2Bwith%2Bpassword.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="480" src="http://2.bp.blogspot.com/-bzgLr91AWcU/VcdkYwrzGYI/AAAAAAAAJzc/F29uQTUzGdY/s640/How%2Bto%2Block%2Bfiles%2Band%2Bfolder%2Bwith%2Bpassword.jpg" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">There are two kinds of file locking:</span><br />
<br />
<ol style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>Exclusive lock</b> : Only one program can hold an exclusive lock on a region of a file</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>Shared lock</b> : Multiple programs can hold shared locks on the same region of a file</span></li>
</ol>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">You <span style="color: blue;">cannot mix</span> an <span style="color: blue;">exclusive </span>lock and a <span style="color: blue;">shared </span>lock on the same region of a file. If a program has a shared lock on a region, another program must wait to get an exclusive lock on that region and vice versa. <span style="color: blue;">Some operating systems do not support a shared file</span> lock, and in that case, the request for a shared file lock is converted to a request for an exclusive file lock.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">How to represent File Lock</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">An object of the <span style="color: blue;"><b>FileLock </b></span>class, which is in the <span style="color: blue;">java.nio.channels</span> package, represents a file lock. You acquire a lock on a file by using the <span style="color: blue;">lock() </span>or <span style="color: blue;">tryLock()</span> method of the <b>FileChannel </b>object</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">The <b>lock()</b> method<span style="color: blue;"> blocks</span> if the lock on the requested region of the file is not available</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">The <b>tryLock()</b> method <span style="color: blue;">does not block</span>; it returns immediately. It returns an object of the FileLock class if the lock was acquired; otherwise, it<span style="color: blue;"> returns null.</span></span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Versions of lock() and tryLock() methods</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Both lock() and tryLock() methods have two versions: one <span style="color: blue;">without an argument</span> and another with <span style="color: blue;">three arguments</span></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">The version without an argument <span style="color: blue;">locks the entire file</span>.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">The version with three arguments accepts the <b>starting </b><span style="color: blue;">position of the region </span>to lock, the <b>number of bytes</b> to lock, and a <b>boolean flag</b> to indicate if the lock is shared. The isShared() method of the FileLock object returns true if the lock is shared; otherwise, it returns false.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Different ways of obtaining locks on a file</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The exception handling code is omitted for readability.</span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-4hjwKAM6N7Q/VcdiVb1GWDI/AAAAAAAAJy8/V3_KAprd_30/s1600/File_locking_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-4hjwKAM6N7Q/VcdiVb1GWDI/AAAAAAAAJy8/V3_KAprd_30/s1600/File_locking_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The file <span style="color: blue;">region that you lock may not be contained in the range of the file size</span>. Suppose you have a file with a size of 100 bytes. When you request a lock on this file, you can specify that you want to lock a region of this file starting at byte 11 and covering 5000 bytes. Note that this file contains only 100 bytes; you are locking 5000 bytes. In such a case, if the file size grows beyond 100 bytes, your lock covers the additional region of the file. Suppose you locked 0 to 100 bytes of a 100-byte file. If this file grows to 150 bytes, your lock does not cover the last 50 bytes that was added after you acquired the lock.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The<b> lock()</b> and <b>tryLock()</b> methods of the FileChannel object, where you <span style="color: blue;">do not specify any argument</span>, lock a region from <span style="color: blue;">0 to Long.MAX_VALUE</span> of the file. The two method calls <span style="color: purple;">f</span><span style="color: blue;">c.lock()</span><span style="color: purple;"> </span>and <span style="color: blue;">fc.lock(0, Long.MAX_VALUE, false)</span> have the <b>same effect</b></span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">How to release the lock</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When you are done with the file lock, you need to release it by using the <span style="color: blue;">release()</span> method. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><b>A file lock is released in three ways:</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">by calling its <span style="color: blue;">release() method</span>, by <span style="color: blue;">closing the file channel </span>it is obtained from, and by <span style="color: blue;">shutting down the JVM</span>. It is good practice to use a try-catch-finally block to acquire and release a file lock as follows:</span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-TtPSgpNsyCE/VcdihF3QBVI/AAAAAAAAJzE/P1HmG-5To2Y/s1600/File_lock_release_syntax_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-TtPSgpNsyCE/VcdihF3QBVI/AAAAAAAAJzE/P1HmG-5To2Y/s1600/File_lock_release_syntax_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In this example, two thread will try to acquire the lock on the same file.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-aU8d9GmKicY/VcdjWaSd_BI/AAAAAAAAJzQ/dbjs0bO7BPM/s1600/File_locking_example_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-aU8d9GmKicY/VcdjWaSd_BI/AAAAAAAAJzQ/dbjs0bO7BPM/s1600/File_locking_example_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Sample output</span><br />
<span style="font-family: Times, Times New Roman, serif;">File is locked by Thread-0</span><br />
<span style="font-family: Times, Times New Roman, serif;">Thread-1 tried to acquire the lock</span><br />
<span style="font-family: Times, 'Times New Roman', serif;">lock is released by Thread-0</span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...</span><br />
<br /></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com65tag:blogger.com,1999:blog-5855689509747625696.post-10613434434350736512015-07-29T23:33:00.000+05:302015-07-29T23:33:26.358+05:30How to Read and Write from RandomAccessFile in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">A <span style="color: blue;">FileInputStream </span>lets you read data from a file whereas a <span style="color: blue;">FileOutputStream </span>lets you write data to a file. A random access file is a combination of both. Using a random access file, you can <span style="color: blue;">read from a file as well as write to the file</span>. Reading and writing using the file input and output streams are a sequential process. Using a random access file, you can read or write at any position within the file (<b>hence the name random access</b>). In this article, we'll try to see how to use <b><a href="http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html" target="_blank">RandomAccessFile </a></b>with the help of an example.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-igsFinRBNgA/VbkUKdrdIXI/AAAAAAAAJxA/-zeHR-5AUNI/s1600/random_access.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="340" src="http://4.bp.blogspot.com/-igsFinRBNgA/VbkUKdrdIXI/AAAAAAAAJxA/-zeHR-5AUNI/s640/random_access.jpg" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">An object of the <b><a href="http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html" target="_blank">RandomAccessFile</a> </b>class facilitates the <span style="color: blue;">random file access</span>. It lets you read/write bytes and all primitive types values to a file. It also lets you work with strings using its <span style="color: blue;">readUTF()</span> and <span style="color: blue;">writeUTF()</span> methods. The RandomAccessFile class is not in the class hierarchy of the <b>InputStream </b>and <b>OutputStream </b>classes</span><br />
<br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Access Mode of Random access file</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A random access file can be created in <span style="color: blue;">four different access modes</span>. In its constructor, you must specify the access mode. The access mode value is a string. They are listed as follows:</span><br />
<br />
<ol style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>"r"</b> : The file is opened in a <span style="color: blue;">read-only </span>mode. You will receive an IOException if you attempt to write to the file.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>"rw"</b> : The file is opened in a <span style="color: blue;">read-write</span> mode. The file is created if it does not exist.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>"rws"</b> : Same as the "rw" mode, except that any modifications to the <span style="color: blue;">file’s content and its metadata</span> are written to the storage device immediately.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>"rwd"</b> : Same as the "rw" mode, except that any modifications to the <span style="color: blue;">file’s content</span> are written to the storage device immediately.</span></li>
</ol>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span></div>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">You create an instance of the RandomAccessFile class by specifying the file name and the access mode as shown:</span></div>
<br />
<div style="text-align: center;">
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");</span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">File Pointer</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A random access file has a<span style="color: blue;"> file pointer</span> that is advanced when you read data from it or write data to it. The file pointer is a kind of cursor where your next read or write will start. Its value <span style="color: blue;">indicates </span>the <span style="color: blue;">distance </span>of the cursor <span style="color: blue;">from the beginning</span> of the file in byes. You can get the value of file pointer by using its <b>getFilePointer()</b> method. When you create an object of the RandomAccessFile class, the<span style="color: blue;"> file pointer is set to <b>zero</b></span>, which indicates the beginning of the file. You can set the file pointer at a specific location in the file using the seek() method.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Length function</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The length() method of a RandomAccessFile returns the current length of the file. You can <span style="color: blue;">extend or truncate</span> a file by using its setLength() method. If you extend a file using this method, the contents of the extended portion of the file are not defined.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Reading from and writing to a random access file is performed the same way you have been reading/writing from/to any input and output streams.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="font-size: large;">Example</span> </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Following example <span style="color: blue;">explain the use of a random access file</span>. When you run this program, it writes two things to a file: the file read counter, which keeps track of how many times a file has been read using this program, and a text message of <span style="color: blue;"><i>"Hello Java Latte"</i></span>. The program increments the counter value in the file every time it reads the file. The counter value keeps incrementing when you run this program repeatedly. You may get a different output every time you run this program.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-AS_4g6Rl3Ew/VbkS3bxl9II/AAAAAAAAJww/JIJce25zE74/s1600/Random_file_access_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-AS_4g6Rl3Ew/VbkS3bxl9II/AAAAAAAAJww/JIJce25zE74/s1600/Random_file_access_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">I hope this example has given you the brief notion of Random Access File class and how it works.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com63tag:blogger.com,1999:blog-5855689509747625696.post-74465993343359251662015-07-25T23:05:00.000+05:302015-07-25T23:05:47.680+05:30Syntax for Lambda expression in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we try to understand the very basic use of Lambda expression with syntax and many examples. If you want to look what is Lambda and the basic idea behind it, I encourage to <a href="http://java-latte.blogspot.in/2014/02/functional-interface-and-lambda-in-java.html" target="_blank"><b>read this my article on the basic</b></a>. I will try to cover all the basic use of Lambda expression in the tutorial.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-VlXwz7kaWBQ/VbPG69YtStI/AAAAAAAAJwY/8lYKCAJctTU/s1600/Lambda_image.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-VlXwz7kaWBQ/VbPG69YtStI/AAAAAAAAJwY/8lYKCAJctTU/s1600/Lambda_image.jpg" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Syntax for Lambda Expressions</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A lambda expression describes an anonymous function. The general syntax for using lambda expressions is very similar to declaring a method. The general syntax is</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-Vwq1I8ssyp0/VbO9F6BbpPI/AAAAAAAAJvg/_99D9sLeIDs/s1600/lambda_syntx_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="60" src="http://2.bp.blogspot.com/-Vwq1I8ssyp0/VbO9F6BbpPI/AAAAAAAAJvg/_99D9sLeIDs/s640/lambda_syntx_java_latte.png" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">A lambda expression consists of <span style="color: blue;">a list of parameters</span> and <span style="color: blue;">a body</span> that are separated by an arrow (->).</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">list of parameters</span> is declared the same way as the list of parameters for methods. The list of parameters is enclosed in parentheses, as is done for methods.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">body of a lambda</span> expression is a block of code enclosed in braces. Like a method's body, the body of a lambda expression may declare local variables; use statements including break, continue, and return; throw exceptions, etc.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Unlike a method, a lambda expression does not have four parts.</span><br />
<br />
<ol style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">A lambda expression <span style="color: blue;">does not have a name</span></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">A lambda expression does <span style="color: blue;">not have a return type</span>. It is inferred by the compiler from the context of its use and from its body</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">A lambda expression <span style="color: blue;">does not have a throws clause.</span> It is inferred from the context of its use and its body.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">A lambda expression <span style="color: blue;">cannot declare type parameters</span>. That is, a lambda expression cannot be generic</span></li>
</ol>
<br />
<br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Basic example to understand Lambda</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Lambda expression are invoked via <span style="color: blue;"><a href="http://java-latte.blogspot.in/2014/02/functional-interface-and-lambda-in-java.html" target="_blank">Function Interface.</a></span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Function Interface</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A functional interface is simply an interface that has exactly one abstract method. The following types of methods in an interface do not count for defining a functional interface:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Default methods</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Static methods</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Public methods inherited from the Object class</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><a href="http://java-latte.blogspot.in/2014/02/functional-interface-and-lambda-in-java.html" target="_blank">More detail on Function detail</a>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Runnable </b>is an example of Function interface, (<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html" target="_blank">check Runnable Java 8 doc</a>) so we can use Runnable interface in term of Lambda expression.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Runnable interface method does not take any input and does not return anything. So it lambda expression will look like</span><br />
<div style="text-align: center;">
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">() -> { statements; }</span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-HNiJbZjD9DA/VbO-fxHRPWI/AAAAAAAAJvs/Jw1Wz5jjDZw/s1600/Lambda_runnable_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-HNiJbZjD9DA/VbO-fxHRPWI/AAAAAAAAJvs/Jw1Wz5jjDZw/s1600/Lambda_runnable_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Similarly, Java 8 has many Functional interface for different purpose. Here is the list of commonly used function interface in the package java.util.function</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-bEaWFKZMdy0/VbO_OQiISnI/AAAAAAAAJv0/P6U7ILnLSR0/s1600/Java_util_Function_interface.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-bEaWFKZMdy0/VbO_OQiISnI/AAAAAAAAJv0/P6U7ILnLSR0/s1600/Java_util_Function_interface.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Following table contains some examples of <span style="color: blue;">lambda expressions and equivalent methods</span>. I have given a suitable name to methods as you cannot have a method without a name in Java. The compiler infers the return type of lambda expressions.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/--3i-atL4QlA/VbPAGWIzxwI/AAAAAAAAJwA/ZVD-z3i4haQ/s1600/Lambda%2BExpressions%2Band%2BEquivalent%2BMethods.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/--3i-atL4QlA/VbPAGWIzxwI/AAAAAAAAJwA/ZVD-z3i4haQ/s1600/Lambda%2BExpressions%2Band%2BEquivalent%2BMethods.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example </b>: how to use above lambda expression with function interface.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-hBPDwH1Y7T0/VbPDd6qNmvI/AAAAAAAAJwM/vVBJ6DdLI6w/s1600/Lambda_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-hBPDwH1Y7T0/VbPDd6qNmvI/AAAAAAAAJwM/vVBJ6DdLI6w/s1600/Lambda_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">One of the goals of the lambda expression was to keep its <span style="color: blue;">syntax concise and let the compiler infer the details</span>. The following sections discuss the shorthand syntax for declaring lambda expressions.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Omitting Parameter Types</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">You can omit the declared type of the parameters. The compiler will infer the types of parameters from the context in which the lambda expression is used</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Types of parameters are declared</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(int x, int y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Types of parameters are omitted</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(x, y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">If you omit the types of parameters, you must omit it for all parameters or for none. You cannot omit for some and not for others. The following lambda expression will not compile because it declares the type of one parameter and omits for the other:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// A compile-time error</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(int x, y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Declaring a Single Parameter</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Sometimes a lambda expression takes only one parameter. You can omit the parameter type for a single parameter lambda expression as you can do for a lambda expression with multiple parameters. You can also omit the parentheses if you omit the parameter type in a single parameter lambda expression. The following are three ways to declare a lambda expression with a single parameter:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Declares the parameter type</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(String msg) -> { System.out.println(msg); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Omits the parameter type</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(msg) -> { System.out.println(msg); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Omits the parameter type and parentheses</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">msg -> { System.out.println(msg); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The parentheses can be omitted only if the single parameter also omits its type. The following lambda expressionwill not compile:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">// Omits parentheses, but not the parameter type, which is not allowed</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">String msg -> { System.out.println(msg); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Declaring No Parameters</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">If a lambda expression does not take any parameters, you need to use empty parentheses.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Takes no parameters</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">() -> { System.out.println("Hello"); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">It is not allowed to omit the parentheses when the lambda expression takes no parameter. The following declaration <span style="color: blue;">will not compile:</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">-> { System.out.println("Hello"); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Parameters with Modifiers</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">You can use modifiers, such as final, in the parameter declaration for explicit lambda expressions. The following two lambda expressions are valid:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">(final int x, final int y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">(int x, final int y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The following lambda expression <span style="color: blue;">will not compile</span> because it uses the final modifier in parameter declarations, but omits the parameter type:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(final x, final y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Declaring Body of Lambda Expressions</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The body of a lambda expression can be <span style="color: blue;">a block statement</span> or <span style="color: blue;">a single expression</span>. A block statement is enclosed in braces; a single expression is not enclosed in braces</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When a block statement is executed the same way as a method’s body. A <span style="color: blue;">return statement </span>or the <span style="color: blue;">end of the body</span> returns the control <span style="color: blue;">to the caller of the lambda</span> expression.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">When an expression is used as the body, <span style="color: blue;">it is evaluated and returned to the caller</span>. If the expression <span style="color: blue;">evaluates to void, nothing is returned to the caller</span>. The following two lambda expressions are the same; one uses a block statement and the other an expression</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Uses a block statement. Takes two int parameters and returns their sum.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(int x, int y) -> { return x + y; }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Uses an expression. Takes a two int parameters and returns their sum.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(int x, int y) -> x + y</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The following two lambda expressions are the same; one uses a block statement as the body and the other an expression that evaluates to void:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Uses a block statement</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">(String msg) -> { System.out.println(msg); }</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// Uses an expression</span><br />
<span style="font-family: 'Trebuchet MS', sans-serif;">(String msg) -> System.out.println(msg)</span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif;"><a href="http://java-latte.blogspot.in/2014/02/lambda-examples-and-effectively-final.html" target="_blank">Check out this link for more examples</a></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<br />
<span style="background-color: white; color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com7tag:blogger.com,1999:blog-5855689509747625696.post-25853893228596059942015-07-25T00:35:00.001+05:302015-07-25T00:35:52.962+05:30How to create thread in Java 8<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we'll see a new way to create thread in Java 8 and also revise the basic two ways to create thread with the help of lambda expression. Main focus of the topic is method reference and how to use thread with lambda expression. If you want to revise the <a href="http://java-latte.blogspot.in/2013/08/basic-of-thread-in-java.html" target="_blank">basic concept of thread check this post</a> and <a href="http://java-latte.blogspot.in/p/java-8.html" target="_blank">this post for lambda concept</a>.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-XXHyGpEUFRo/VbKLUZmhNNI/AAAAAAAAJvA/eRoa2AVfGkc/s1600/Simple_thread_execution_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-XXHyGpEUFRo/VbKLUZmhNNI/AAAAAAAAJvA/eRoa2AVfGkc/s1600/Simple_thread_execution_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Creating a Thread in Java</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The Java API makes it easy to work with threads. It lets you represent a thread as an object. An object of the <span style="color: blue;">java.lang.Thread </span>class represents a thread. Creating and using a thread in Java is as simple as creating an object of the Thread class and using that object in a program. Let’s start with the simplest example of creating a thread in Java. There are at least two steps involved in working with a thread:</span><br />
<br />
<ol style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Creating an object of the Thread class</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Invoking the<span style="color: blue;"> start()</span> method of the Thread class to start the thread</span></li>
</ol>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">Creating an object of the Thread class is the same as creating an object of any other classes in Java. In its simplest form, you can use the default constructor of the Thread class to create a Thread object.</span><br />
<div style="text-align: center;">
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">// create a new thread</span></div>
<div style="text-align: center;">
<span style="font-family: Trebuchet MS, sans-serif;"><b>Thread simpleThread = new Thread();</b></span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Creating an object of the Thread class allocates memory for that object on the heap. It does not start or run the thread. After you have created an object of the Thread class, you must call its start() method to start the thread represented by that object.</span><br />
<div style="text-align: center;">
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">//start the thread</span></div>
<div style="text-align: center;">
<b style="font-family: 'Trebuchet MS', sans-serif;">simpleThread.start();</b></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b> </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-zS2gjIWM6gk/VbKJFsC6LqI/AAAAAAAAJuQ/IQ0UH1XREzg/s1600/Simple__thread_example_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-zS2gjIWM6gk/VbKJFsC6LqI/AAAAAAAAJuQ/IQ0UH1XREzg/s1600/Simple__thread_example_in_java_latte.png" /></a></div>
<span style="font-family: 'Trebuchet MS', sans-serif;">The start() method returns after doing some housekeeping work. It puts the thread in the runnable state. In this state, the thread is ready to receive the CPU time. Note that invoking the start() method of a Thread object does not guarantee “when” this thread will start getting the CPU time. That is, it does not guarantee when the thread will start running. It just schedules the thread to receive the CPU time.</span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Three ways to create thread</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">There are three ways you can specify your code to be executed by a thread</span><br />
<br />
<ol style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">By <span style="color: blue;">inheriting</span> your class from the Thread class</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">By <span style="color: blue;">implementing </span>the Runnable interface in your class</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">By using the <span style="color: blue;"><a href="http://java-latte.blogspot.in/2014/03/method-references-in-java-8.html" target="_blank">method reference</a></span> to a method that takes no parameters and returns void</span></li>
</ol>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">Inheriting Your Class from the Thread Class</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When you inherit your class from the Thread class, you should <span style="color: blue;">override the run()</span> method and provide the code to be executed by the thread.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-QHoJBfuY_tM/VbKJpH_J7SI/AAAAAAAAJuY/S2rTsycGNbI/s1600/Thread_inherit_demo_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-QHoJBfuY_tM/VbKJpH_J7SI/AAAAAAAAJuY/S2rTsycGNbI/s1600/Thread_inherit_demo_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">Implementing the Runnable Interface</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">You can create a class that implements the java.lang.Runnable interface. Runnable is a <a href="http://java-latte.blogspot.in/2014/02/functional-interface-and-lambda-in-java.html" target="_blank">functional interface</a> and it is declared as follows</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">@<a href="http://java-latte.blogspot.in/2014/02/functional-interface-and-lambda-in-java.html" target="_blank">FunctionalInterface</a></span><br />
<b style="font-family: 'Trebuchet MS', sans-serif;">public interface Runnable</b><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://2.bp.blogspot.com/-y5a5tB9Ny5E/VbKKTTuQjRI/AAAAAAAAJuo/b_2rsfS_uX4/s1600/function_interface_example_java_latte.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="http://2.bp.blogspot.com/-y5a5tB9Ny5E/VbKKTTuQjRI/AAAAAAAAJuo/b_2rsfS_uX4/s1600/function_interface_example_java_latte.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><br /></td></tr>
</tbody></table>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;">Using a Method Reference</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Check this post for detail on <a href="http://java-latte.blogspot.in/2014/03/method-references-in-java-8.html" target="_blank">method reference</a>. From Java 8, you can use the method reference of a method of any class that <span style="color: blue;">takes no parameters and returns void</span> as the code to be executed by a thread.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The following code declares a ThreadTest class that contains an execute() method. The method contains the code to be executed in a thread.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-5YmaYiHepo4/VbKK1uh5KoI/AAAAAAAAJuw/WRD1Plm35_4/s1600/method_reference_Thread_demo_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-5YmaYiHepo4/VbKK1uh5KoI/AAAAAAAAJuw/WRD1Plm35_4/s1600/method_reference_Thread_demo_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The thread will execute the code contained in the execute() method of the ThreadTest class</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Final example</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-e31FiR0mmO4/VbKMW9__9DI/AAAAAAAAJvM/23AVtPlsuxs/s1600/method_reference_Thread_demo_java_latte_2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-e31FiR0mmO4/VbKMW9__9DI/AAAAAAAAJvM/23AVtPlsuxs/s1600/method_reference_Thread_demo_java_latte_2.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com11tag:blogger.com,1999:blog-5855689509747625696.post-8760024589758084242015-07-21T00:30:00.000+05:302015-07-21T00:30:17.161+05:30DelayQueue class and Delayed interface example in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we look into one of the implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take i.e, DelayQueue. An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. We'll try to understand the concept of <b>DelayQueue </b>class and <b>Delayed </b><span style="color: blue;">interface </span>with the help of example.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-Q-DZKZHz43M/Va1FHo6LixI/AAAAAAAAJtw/Q5CoFt7XSKA/s1600/queue.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="358" src="http://1.bp.blogspot.com/-Q-DZKZHz43M/Va1FHo6LixI/AAAAAAAAJtw/Q5CoFt7XSKA/s640/queue.png" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">What is DelayQueue?</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">An <span style="color: blue;">unbounded blocking queue</span> of <b>Delayed </b><span style="color: blue;">elements</span>, in which an element can only be taken when its delay has expired. In this class, you can store elements with an activation date. The methods that return or extract elements of the queue will<span style="color: blue;"> ignore those elements whose data is in the future</span>. They are invisible to those methods. Here Delayed elements are those elements who implements Delayed interface.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">What is Delayed Interface?</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A mix-in style interface for marking objects that should be acted upon after a given delay.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">This interface allows you to work with delayed objects, so you will implement the activation date of the objects stored in the DelayedQueue class as the time remaining until the activation date. This interface forces to implement the following two methods</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;"><b>compareTo(Delayed o)</b></span>: The Delayed interface extends the <span style="color: blue;"><a href="http://java-latte.blogspot.in/2014/02/comparable-and-comparator-interfaces-in.html" target="_blank">Comparable interface</a></span>. This method will return a value <span style="color: blue;">less than zero</span> if the object that is executing the method has a delay smaller than the object passed as a parameter, a value <span style="color: blue;">greater than zero</span> if the object that is executing the method has a delay bigger than the object passed as a parameter, and the <span style="color: blue;">zero value</span> if both objects have the same delay.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"> <b><span style="color: blue;">getDelay(<a href="http://java-latte.blogspot.in/2014/04/TimeUnit-Enum-in-Java-Concurrency.html" target="_blank">TimeUnit </a>unit)</span></b>: This method has to return the time remaining until the activation date in the units is specified by the unit parameter. The <a href="http://java-latte.blogspot.in/2014/04/TimeUnit-Enum-in-Java-Concurrency.html" target="_blank">TimeUnit </a>class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">The head of the queue is that Delayed element whose delay expired furthest in the past. If no delay has expired there is no head and poll will return null. Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero. Even though unexpired elements cannot be removed using take or poll, they are otherwise treated as normal elements. This queue does <span style="color: blue;">not permit null</span> elements.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-R5Zz-ND0EAc/Va1A4_aensI/AAAAAAAAJtE/DBP2Oc_t6YY/s1600/DelayedQueue_and_delayed_interface_java_latte.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-R5Zz-ND0EAc/Va1A4_aensI/AAAAAAAAJtE/DBP2Oc_t6YY/s1600/DelayedQueue_and_delayed_interface_java_latte.jpg" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Example</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In this example, you will learn how to use the DelayedQueue class storing in it some events </span><span style="font-family: 'Trebuchet MS', sans-serif;">with different activation dates</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">we have implemented the Event class. That class has a unique attribute, the activation date of the events, and implements the Delayed interface, so you can store Event objects in the DelayedQueue class.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-qNUynQWHK_w/Va1BU7IUVlI/AAAAAAAAJtM/OfGTXc9dIjg/s1600/Delayed_interface_Event_class_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-qNUynQWHK_w/Va1BU7IUVlI/AAAAAAAAJtM/OfGTXc9dIjg/s1600/Delayed_interface_Event_class_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The <b>getDelay()</b> method returns the number of <span style="color: blue;">nanoseconds </span>between the<span style="color: blue;"> activation date and the actual date</span>. Both dates are objects of the Date class. You have used the getTime() method that returns a <span style="color: blue;">date converted to milliseconds </span>and then, you have converted that value to TimeUnit received as a parameter. The DelayedQueue class works in nanoseconds, but at this point, it's transparent to you.</span><br />
<br />
<span style="font-family: Trebuchet MS, sans-serif;">The <b>compareTo()</b> method returns a value less than zero if the delay of the object executing the method is smaller than the delay of the object passed as a parameter, a value greater than zero if the delay of the object executing the method is bigger than the delay of the object passes as a parameter, and the value 0 if both delays are equal.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-smp0YT3NUj0/Va1BvMTl17I/AAAAAAAAJtU/V6dGsousWhU/s1600/Delayed_task_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-smp0YT3NUj0/Va1BvMTl17I/AAAAAAAAJtU/V6dGsousWhU/s1600/Delayed_task_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;">This class has an integer attribute named id. When a Task object is executed, it adds a number of seconds equal to the ID of the task to the actual date and that is the activation date of the events stored by this task in </span><span style="font-family: 'Trebuchet MS', sans-serif;">the DelayedQueue class. Each Task object stores 10 events in the queue using the add() method.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-sVU87w3OUQo/Va1B50AgzhI/AAAAAAAAJtc/0afmeqfe0_s/s1600/DelayedQueue_demo_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-sVU87w3OUQo/Va1B50AgzhI/AAAAAAAAJtc/0afmeqfe0_s/s1600/DelayedQueue_demo_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Finally, in the main() method of the Main class, you have created sixTask objects and executed them in the corresponding threads. When those threads finish their execution, you have written to the console all the events using the poll() method. That method retrieves and removes the first element of the queue. If the queue does not have any active element, the method returns the null value. You called the poll() method and if it returns an Event class, you increment a counter. When the poll() method returns the null value, you write the value of the counter in the console and put the thread to sleep during half a second to wait for more active events. When you have obtained the 500 events stored in the queue, the execution of the program finishes</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-S9yxFbu1tWU/Va1CEqUN7ZI/AAAAAAAAJtk/MoFOOSUkqUQ/s1600/DelayedQueue_example_output_java_Latte.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-S9yxFbu1tWU/Va1CEqUN7ZI/AAAAAAAAJtk/MoFOOSUkqUQ/s1600/DelayedQueue_example_output_java_Latte.jpg" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">You can see how the program only gets 10 events when it is activated.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The DelayQueue class has other interesting methods, which are as follows:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>clear()</b>: This method removes all the elements of the queue.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>offer(E e)</b>: E represents the class used to parameterize the DelayQueue class. This method inserts the element passed as a parameter in the queue.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>peek()</b>: This method retrieves, but doesn't remove the first element of the queue.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>take()</b>: This method retrieves and removes the first element of the queue. If there aren't any active elements in the queue, the thread that is executing the method will be blocked until the thread has some active elements.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18px;">If you know anyone who has started learning Java, why not help them out! Just share this post with them. </span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18px;">Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com3tag:blogger.com,1999:blog-5855689509747625696.post-84776122358580037762015-04-03T12:13:00.000+05:302015-04-03T12:13:32.115+05:30newFixedThreadPool, Callable and Future example in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we will learn how to implement tasks that return a result and run them on an executor using <span style="color: blue;">Callable </span>and <span style="color: blue;">Future </span>interfaces with the help Executor framework. This post is continuation of <a href="http://java-latte.blogspot.in/2015/04/newcachedthreadpool-ThreadPoolExecutor-example-in-java.html" target="_blank">previous post</a> where we learned about <a href="http://java-latte.blogspot.in/2015/04/newcachedthreadpool-ThreadPoolExecutor-example-in-java.html" target="_blank">cached Thread pool</a></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">One of the advantages of the Executor framework is that you can run concurrent tasks that return a result. The Java Concurrency API achieves this with the following two interfaces:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>Callable</b>: This interface has the call() method. In this method, you have to implement the logic of a task. The Callable interface is a parameterized interface, meaning you have to indicate the type of data the call() method will return.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>Future</b>: This interface has some methods to obtain the result generated by a Callable object and to manage its state</span></li>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-cNdm3aWSrN0/VR41vuWwwlI/AAAAAAAAJRc/kVjNhpMSn7o/s1600/Thread_pool.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-cNdm3aWSrN0/VR41vuWwwlI/AAAAAAAAJRc/kVjNhpMSn7o/s1600/Thread_pool.jpg" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Create a class named <b>FactCalculator </b>that implements the <span style="color: blue;">Callable </span>interface parameterized with the Integer type</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-nqfldz_QCwk/VR4qRTeHnAI/AAAAAAAAJQ4/KNALaG_Cxl0/s1600/Callable_interface_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-nqfldz_QCwk/VR4qRTeHnAI/AAAAAAAAJQ4/KNALaG_Cxl0/s1600/Callable_interface_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Implement the <b>Main </b>class</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-zfKKdqWtq4k/VR4qTNL_EFI/AAAAAAAAJRA/gyv9808lHJA/s1600/newFixedThreadPool-Callable-Future-example-in-Java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-zfKKdqWtq4k/VR4qTNL_EFI/AAAAAAAAJRA/gyv9808lHJA/s1600/newFixedThreadPool-Callable-Future-example-in-Java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<b style="font-family: 'Trebuchet MS', sans-serif;">Output</b><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 0</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 1</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 2</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 3</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 3</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 4</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 4</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 6</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 6</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 8</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 8</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Number of completed task : 8</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 0 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 1 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 2 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 3 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 4 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 5 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 6 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 7 status : true</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 8 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Task 9 status : false</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Main result : </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 0 2</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 1 120</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 2 6</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 3 720</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 4 362880</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 5 362880</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 6 2</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 7 24</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"> Result of Task: 8 40320</span><br />
<span style="font-family: 'Trebuchet MS', sans-serif;"> Result of Task: 9 40320</span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">How it works...</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In this example, we have learned how to use the <span style="color: blue;">Callable interface</span> to launch concurrent tasks that <span style="color: blue;">return a result</span>. You have implemented the FactorialCalculator class that implements the Callable interface with Integer as the type of the result. Hence, it returns before type of the call() method.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The other important point of this example is in the Main class. You send a <span style="color: blue;">Callable object to be executed in an executor</span> using the <span style="color: blue;">submit</span>() method. This method receives a Callable object as a parameter and <span style="color: blue;">returns a Future object</span> that you can use with two main objectives</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">You can <span style="color: blue;">control the status of the task</span>: you can <span style="color: blue;">cancel the task</span> and check if it has finished. For this purpose, you have used the isDone() method to check if the tasks had finished.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">You can <span style="color: blue;">get the result</span> returned by the <span style="color: blue;">call() method</span>. For this purpose, you have used the get() method. This method waits until the Callable object has finished the execution of the call() method and has returned its result. If the thread is interrupted while the get() method is waiting for the result, it throws an InterruptedException exception. If the call() method throws an exception, this method throws an ExecutionException exception.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span></div>
<div>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">There's more...</span></div>
<div>
<span style="font-family: 'Trebuchet MS', sans-serif;">When you call the get() method of a Future object and the task controlled by this object hasn't finished yet, the method blocks until the task finishes. The </span><span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">Future</span><span style="font-family: 'Trebuchet MS', sans-serif;"> interface provides </span><span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">another version of the get()</span><span style="font-family: 'Trebuchet MS', sans-serif;"> method.</span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">get(long timeout, TimeUnit unit)</span>: This version of the get method, if the result of the task isn't available, waits for it for the specified time. If the specified period of time passes and the result isn't yet available, the method returns a null value. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">That's all. Thanks for reading this and if you found this article useful, I would like to see your appreciation in the form of comments.</span><br style="background-color: white; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;" /><span style="background-color: white; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"><br /></span><span style="background-color: white; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;"></span><span style="background-color: white; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"><br /></span><span style="background-color: white; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;"></span><span style="background-color: white; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"><br /></span><span style="background-color: white; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px;"></span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning J</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">ava</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com3tag:blogger.com,1999:blog-5855689509747625696.post-20458043800424528512015-04-02T12:18:00.000+05:302015-04-02T12:18:24.986+05:30newCachedThreadPool example in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">The first step to work with the Executor framework is to create an object of the ThreadPoolExecutor class. You can use the four constructors provided by that class or use a factory class named <b>Executors </b>that creates ThreadPoolExecutor. Once you have an executor, you can send Runnable or Callable objects to be executed. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In this article, you will learn how these two operations implement an example that will simulate a server processing requests from various clients. Before that you can have an overview of Executor frameworks in my <a href="http://java-latte.blogspot.in/2014/03/executor-executorservice-threadpool-and.html" target="_blank">previous article</a>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-DnWlxsulSZE/UzFx9CD5dMI/AAAAAAAAE8Y/Ydw7MTUdbmg/s1600/excutor_diagram_java_latte_blogspot_in.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-DnWlxsulSZE/UzFx9CD5dMI/AAAAAAAAE8Y/Ydw7MTUdbmg/s1600/excutor_diagram_java_latte_blogspot_in.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">First, you have to implement the tasks that will be executed by the server. Create a class named <b>Task </b>that implements the Runnable interface</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-KkVE1MTN_0c/VRzOzsdTDgI/AAAAAAAAJQI/wsCYqstbnQ0/s1600/newCachedThreadPool_task_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-KkVE1MTN_0c/VRzOzsdTDgI/AAAAAAAAJQI/wsCYqstbnQ0/s1600/newCachedThreadPool_task_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Now, implement the <b>CachedPoolServer </b>class that will execute every task it receives using an executor</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-zYFw0Lib-Fo/VRzOykErChI/AAAAAAAAJP8/IUrT3MhVq1s/s1600/newCachedThreadPool_creation_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-zYFw0Lib-Fo/VRzOykErChI/AAAAAAAAJP8/IUrT3MhVq1s/s1600/newCachedThreadPool_creation_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Finally, implement the main class of the example by creating a class named <b>Main </b>and implement the main() method</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-XR8gQgwLVrI/VRzOypOAMCI/AAAAAAAAJQE/kjlnO7sHp9I/s1600/newCachedThreadPool_demo_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-XR8gQgwLVrI/VRzOypOAMCI/AAAAAAAAJQE/kjlnO7sHp9I/s1600/newCachedThreadPool_demo_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">How it works...</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The main part of this example is the CachedPoolServer class. This class creates and uses ThreadPoolExecutor to execute tasks</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">first important point</span> is the <span style="color: blue;">creation of ThreadPoolExecutor</span> in the constructor of the Server class. The ThreadPoolExecutor class has <span style="color: blue;">four different constructors</span> but, due to their <span style="color: blue;">complexity</span>, the Java concurrency API provides the <b>Executors </b>class to construct executors and other related objects. Although we can create threadPoolExecutor directly using one of its constructors, it's <span style="color: blue;">recommended to use the Executors class</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In this case, you have created a cached thread pool using the <span style="color: blue;">newCachedThreadPool</span>() method. This method <span style="color: blue;">returns an ExecutorService object</span>, so it's been<span style="color: blue;"> cast to ThreadPoolExecutor</span> to have access to all its methods. The cached thread pool you have created creates new threads if needed to execute the <span style="color: blue;">new tasks, and reuses the existing </span>ones if they have finished the execution of the task they were running, which are now available. The <b>reutilization of threads has the <span style="color: blue;">advantage </span>that it reduces the time taken for thread creation</b>. The cached thread pool has, however, a <span style="color: red;">disadvantage</span> of constant lying threads for new tasks, so if you send too many tasks to this executor, you can <span style="color: blue;">overload the system</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Tip</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Use the executor created by the newCachedThreadPool() method only when you have a <span style="color: blue;">reasonable number of threads</span> or when they have a <span style="color: blue;">short duration</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Once you have created the executor, you can send tasks of the <span style="color: blue;">Runnable </span>or <span style="color: blue;"><a href="http://java-latte.blogspot.in/2014/03/executor-executorservice-threadpool-and.html" target="_blank">Callable </a></span>type for execution using the execute() method. In this case, you send objects of the Task class that implements the Runnable interface.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">We also have printed some log messages with information about the executor. Specifically, you have used the following methods:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>getPoolSize</b>(): This method returns the actual number of threads in the pool of the executor</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>getActiveCount</b>(): This method returns the number of threads that are executing tasks in the executor.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>getCompletedTaskCount</b>(): This method returns the number of tasks completed by the executor</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue;">One critical aspect </span></b>of the ThreadPoolExecutor class, and of the executors in general, is that you have to <span style="color: blue;">end it explicitly</span>. If you don't do this, the executor will continue its execution and the program won't end. If the executor doesn't have tasks to execute, it continues waiting for new tasks and it doesn't end its execution. A Java application won't end until all its non-daemon threads finish their execution, so, if you don't terminate the executor, your application will never end.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">To indicate to the executor that you want to finish it, you can use the <span style="color: blue;">shutdown</span>() method of the <span style="color: blue;">ThreadPoolExecutor </span>class. When the executor finishes the execution of all pending tasks, it finishes its execution. After you call the shutdown() method, if you try to send another task to the executor, it will be rejected and the executor will throw a <span style="color: red;">RejectedExecutionException </span>exception. The following screenshot shows part of one execution of this example:</span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-0BlEJm5xoJY/VRzR30enlNI/AAAAAAAAJQg/blASHzZ5-Uo/s1600/newCachedThreadPool_output.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-0BlEJm5xoJY/VRzR30enlNI/AAAAAAAAJQg/blASHzZ5-Uo/s1600/newCachedThreadPool_output.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">There's more...</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The ThreadPoolExecutor class <span style="color: blue;">provides a lot of methods</span> to obtain information about its status. We used in the example the getPoolSize(), getActiveCount(), and getCompletedTaskCount() methods to obtain information about the size of the pool, the number of threads, and the number of completed tasks of the executor. You can also use the getLargestPoolSize() method that returns the maximum number of threads that has been in the pool at a time.</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>shutdownNow</b>(): This method shut downs the executor immediately. It doesn't execute the pending tasks. It returns a list with all these pending tasks. The tasks that are running when you call this method continue with their execution, but the method doesn't wait for their finalization.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>isTerminated</b>(): This method returns true if you have called the shutdown() or shutdownNow() methods and the executor finishes the process of shutting it down.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>isShutdown</b>(): This method returns true if you have called the shutdown() method of the executor.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>awaitTermination</b><span style="color: blue;">(long timeout, TimeUnit unit)</span>: This method blocks the calling thread until the tasks of the executor have ended or the timeout occurs. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS</span></li>
</ul>
<br />
<br />
<span style="font-family: Trebuchet MS, sans-serif;">That's all. Thanks for reading this and if you found this article useful, I would like to see your appreciation in the form of comments.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;">If you know anyone who has started learning </span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;">java</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;">, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com25tag:blogger.com,1999:blog-5855689509747625696.post-19499014083301414572015-03-20T12:00:00.000+05:302015-03-21T12:17:23.376+05:30ReadWriteLock example in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">One of the most significant improvements offered by locks is the <span style="color: blue;">ReadWriteLock </span>interface and the <span style="color: blue;">ReentrantReadWriteLock </span>class, the unique one that implements it. This class has two locks, one for read operations and one for write operations. There can be more than one thread using read operations simultaneously, but only one thread can be using write operations. When a thread is doing a write operation, there can't be any thread doing read operations.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/--2xFXAGWCcY/VQu9-n5Wm2I/AAAAAAAAJNM/h0-pWMcYhPI/s1600/ReadWriteLock_image_java_latte.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/--2xFXAGWCcY/VQu9-n5Wm2I/AAAAAAAAJNM/h0-pWMcYhPI/s1600/ReadWriteLock_image_java_latte.gif" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In this article, you will learn how to use a ReadWriteLock interface implementing a program that uses it to control the access to an object that stores the prices of two books</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>BookInfo class</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><b><br /></b></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-Z8gE5u-Z_Nk/VQ0T43qquKI/AAAAAAAAJNc/tTyx8nvzVsU/s1600/ReadWriteLock_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-Z8gE5u-Z_Nk/VQ0T43qquKI/AAAAAAAAJNc/tTyx8nvzVsU/s1600/ReadWriteLock_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b><br /></b></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;">Create a class named <b>Reader </b>and specify that it implements the Runnable interface. This class implements a reader of the values of the BookInfo class attributes.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-GzpnWMoKoLc/VQu6nLRjj9I/AAAAAAAAJM0/7RSdfrKXegg/s1600/ReadWriteLock_reader_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-GzpnWMoKoLc/VQu6nLRjj9I/AAAAAAAAJM0/7RSdfrKXegg/s1600/ReadWriteLock_reader_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Create a class named <b>Writer </b>and specify that it implements the Runnable interface. This class implements a modifier of the values of the BookInfo class attributes.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-riXWDdbhVu4/VQu6n2csDqI/AAAAAAAAJM8/w8tCXZ_aS5E/s1600/ReadWriteLock_writer_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-riXWDdbhVu4/VQu6n2csDqI/AAAAAAAAJM8/w8tCXZ_aS5E/s1600/ReadWriteLock_writer_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Main class</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-g6cSK8sTOA8/VQu6nLRHDQI/AAAAAAAAJMs/gHCeBhRx-As/s1600/ReadWriteLock_Main_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-g6cSK8sTOA8/VQu6nLRHDQI/AAAAAAAAJMs/gHCeBhRx-As/s1600/ReadWriteLock_Main_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">As we mentioned previously, the ReentrantReadWriteLock class has<span style="color: blue;"> two locks</span>, one for <span style="color: blue;">read operations</span> and one for <span style="color: blue;">write operations</span>. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The lock used in read operations is obtained with the readLock() method declared in the ReadWriteLock interface. This lock is an object that implements the Lock interface, so we can use the lock(), unlock(), and tryLock() methods. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The lock used in write operations is obtained with the <span style="color: blue;">writeLock</span>() method declared in the ReadWriteLock interface. This lock is an object that implements the Lock interface, so we can use the lock(), unlock(), and tryLock() methods.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">It is the responsibility of the programmer to ensure the correct use of these locks, using them with the same purposes for which they were designed.When you get the read lock of a Lock interface, you can't modify the value of the variable. Otherwise, you probably will have inconsistency data errors.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning </span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">java</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">, why not help them out! Just share this post with them. Thanks for studying today!...</span><br />
<br /></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-4519587132959892332015-03-20T10:16:00.000+05:302015-03-20T10:16:34.096+05:30Producer Consumer problem in Java using wait and notify<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">A classic problem in concurrent programming is the <span style="color: blue;">producer-consumer problem</span>. We have a data buffer, one or more producers of data that save it in the buffer and one or more consumers of data that take it from the buffer.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">As the <span style="color: blue;">buffer </span>is a <span style="color: blue;">shared data structure</span>, we have to control the access to it using a synchronization mechanism such as the synchronized keyword, but we have more limitations. A producer <span style="color: blue;">can't save data in the buffer if it's full</span> and the consumer <span style="color: blue;">can't take data from the buffer if it's empty</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-ShXKcDKNewQ/VQshJ7oZ4wI/AAAAAAAAJMY/kXO7Kter6c4/s1600/Producer_consumer_main_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-ShXKcDKNewQ/VQshJ7oZ4wI/AAAAAAAAJMY/kXO7Kter6c4/s1600/Producer_consumer_main_java_latte.png" height="238" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">For these types of situations, Java provides the <span style="color: blue;">wait(), notify(), and notifyAll()</span> methods implemented in the Object class. A thread can call the wait() method inside a synchronized block of code. If it calls the wait() method outside a synchronized block of code, the JVM throws an IllegalMonitorStateException exception. When the thread calls the wait() method, the JVM <span style="color: blue;">puts the thread to sleep</span> and releases the object that controls the synchronized block of code that it's executing and allows the other threads to execute other blocks of synchronized code protected by that object. To wake up the thread, you must <span style="color: blue;">call the notify() or notifyAll()</span> method inside a block of code protected by the same object.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In this article, you will learn how to implement the producer-consumer problem using the synchronized keyword and the wait(), notify(), and notifyAll() methods</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>Storage class</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">It has two attributes: an int attribute called maxSize and a LinkedList<Date> attribute called list.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Implement the <span style="color: blue;">synchronized </span>method <b>set()</b> to store an event in the storage. First, check if the storage is full or not. If it's full, it calls the wait() method until the storage has empty space. At the end of the method, we call the notifyAll() method to wake up all the threads that are sleeping in the wait() method.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Implement the <span style="color: blue;">synchronized </span>method <b>get()</b> to get an event for the storage. First, check if the storage has events or not. If it has no events, it calls the wait() method until the storage has some events. At the end of the method, we call the notifyAll() method to wake up all the threads that are sleeping in the wait() method.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-EM5FTsds7es/VQsfTJtZQTI/AAAAAAAAJMM/oPdsdI7Aa1M/s1600/Storage_for_producer_consumer_java_example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-EM5FTsds7es/VQsfTJtZQTI/AAAAAAAAJMM/oPdsdI7Aa1M/s1600/Storage_for_producer_consumer_java_example.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>Producer and Consumer</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Create a class named Producer and Consumer and specify that it implements the Runnable interface. </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-HT4w5re2F1o/VQsfSVdT1oI/AAAAAAAAJL8/QzaGiv0JrgE/s1600/Producer_consumer_example_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-HT4w5re2F1o/VQsfSVdT1oI/AAAAAAAAJL8/QzaGiv0JrgE/s1600/Producer_consumer_example_java.png" /></a></div>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>Main Class</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-EYv7tLsoL4Q/VQsfSRiDviI/AAAAAAAAJL4/stuwiJ5vF4E/s1600/Producer_consumer_main_program_example_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-EYv7tLsoL4Q/VQsfSRiDviI/AAAAAAAAJL4/stuwiJ5vF4E/s1600/Producer_consumer_main_program_example_java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Sample Output</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-XbtVLsikTyA/VQsfSK1UUqI/AAAAAAAAJL0/4a5PEq0Zy78/s1600/Producer_consumer_example_java_output.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-XbtVLsikTyA/VQsfSK1UUqI/AAAAAAAAJL0/4a5PEq0Zy78/s1600/Producer_consumer_example_java_output.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">How it works...</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The key to this example is the set() and get() methods of the EventStorage class. First of all, the set() method checks if there is free space in the storage attribute. If it's full, it calls the wait() method to wait for free space. When the other thread calls the notifyAll() method, the thread wakes up and checks the condition again. The notifyAll() method doesn't guarantee that the thread will wake up. This process is repeated until there is free space in the storage and it can generate a new event and store it.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The behavior of the get() method is similar. First, it checks if there are events on the storage. If the EventStorage class is empty, it calls the wait() method to wait for events. Where the other thread calls the notifyAll() method, the thread wakes up and checks the condition again until there are some events in the storage.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">If you run this example, you will see how producer and consumer are setting and getting the events, but the storage never has more than 10 events.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning </span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">java</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">, why not help them out! Just share this post with them. Thanks for studying today!...</span><br />
<br /></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-59311976085152347992015-03-19T23:43:00.000+05:302015-03-19T23:48:53.320+05:30UncaughtExceptionHandler in Java <div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">UncaughtExceptionHandler is interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. Basically, this is a mechanism to catch and treat the unchecked exception thrown in a thread object that what we are going to see in this article.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-i7TGqQpxFxQ/VQsRQ-dfroI/AAAAAAAAJLk/CCe6-lKOMpg/s1600/UncaughtExceptionHandler_main_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-i7TGqQpxFxQ/VQsRQ-dfroI/AAAAAAAAJLk/CCe6-lKOMpg/s1600/UncaughtExceptionHandler_main_java_latte.png" height="235" width="640" /></a></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">There are two kinds of exceptions in Java:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><a href="http://java-latte.blogspot.in/2013/11/user-defined-exception-in-java.html" target="_blank">Checked exceptions</a>:</b> These exceptions must be specified in the throws clause of a method or caught inside them. For example, IOException or classNotFoundException.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><a href="http://java-latte.blogspot.in/2013/11/user-defined-exception-in-java.html" target="_blank">Unchecked exceptions</a>:</b> These exceptions don't have to be specified or caught. For example, NumberFormatException.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">When a checked exception is thrown inside the run() method of a Thread object, we have to catch and treat them, because the run() method doesn't accept a throws clause. When an unchecked exception is thrown inside the run() method of a Thread object, the default behaviour is to write the stack trace in the console and exit the program</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Fortunately, Java provides us with a <span style="color: blue;">mechanism to catch and treat the unchecked exceptions</span> thrown in a Thread object to avoid the program ending</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">First of all, we have to implement a class to treat the unchecked exceptions. This class must implement the UncaughtExceptionHandler interface and implement the uncaughtException() method declared in that interface. In our case, call this class ExceptionHandler and make the method to write information about Exception and Thread that threw it. Following is the code:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-okCJBgFD-Oc/VQsPVHv1zFI/AAAAAAAAJLI/fAbgicThyBw/s1600/UncaughtExceptionHandler_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-okCJBgFD-Oc/VQsPVHv1zFI/AAAAAAAAJLI/fAbgicThyBw/s1600/UncaughtExceptionHandler_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Now, implement a class that throws an unchecked exception</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-pVJQ3vg7NkY/VQsPeNSRm-I/AAAAAAAAJLQ/tdurfGoYcMQ/s1600/UncaughtExceptionHandler_task_example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-pVJQ3vg7NkY/VQsPeNSRm-I/AAAAAAAAJLQ/tdurfGoYcMQ/s1600/UncaughtExceptionHandler_task_example.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;">Now, implement the main class of the example</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-0XHopZRwYcY/VQsPfRsjBeI/AAAAAAAAJLY/UV2FsPur2mA/s1600/UncaughtExceptionHandler_main_example_java_Latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-0XHopZRwYcY/VQsPfRsjBeI/AAAAAAAAJLY/UV2FsPur2mA/s1600/UncaughtExceptionHandler_main_example_java_Latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">When an exception is thrown in a thread and is not caught (it has to be an unchecked exception), the JVM checks if the thread has an uncaught exception handler set by the corresponding method. If it has, the JVM invokes this method with the Thread object and Exception as arguments.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">If the thread has not got an uncaught exception handler, the JVM prints the stack trace in the console and exits the program.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>There is more....</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The Thread class has another method related to the process of uncaught exceptions. It's the static method setDefaultUncaughtExceptionHandler() that establishes an exception handler for all the Thread objects in the application. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">When an uncaught exception is thrown in Thread, the JVM looks for <span style="color: blue;">three possible handlers</span> for this exception.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">First, it looks for the uncaught exception handler of the Thread objects as we learned in this recipe. If this handler doesn't exist, then the JVM looks for the uncaught exception handler for ThreadGroup of the Thread objects as was explained in the Processing uncontrolled exceptions in a group of threads recipe. If this method doesn't exist, the JVM looks for the default uncaught exception handler as we learned in this recipe.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">If none of the handlers exits, the JVM writes the stack trace of the exception in the console and exits the program.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<br />
<br />
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning </span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">java</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-66116895628958921182015-02-22T11:47:00.000+05:302015-05-27T12:59:49.168+05:30Cloning Objects in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality. In this article, we look into the basic of cloning in Java and types of cloning such as shallow and deep cloning. Also, it disadvantages and what are the alternative approach to do the cloning in Java.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-SCzvCSJD8IE/VOjfL_C5m9I/AAAAAAAAJEg/OrbkYyzScyI/s1600/Human-Cloning.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-SCzvCSJD8IE/VOjfL_C5m9I/AAAAAAAAJEg/OrbkYyzScyI/s1600/Human-Cloning.jpg" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Java does not provide an <span style="color: blue;">automatic mechanism</span> to <b>clone </b>(make a copy) an object. Recall that when you assign a reference variable to another reference variable, only the reference of the object is copied, not the content of the object. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">Cloning an object means</span> copying the content of the object bit by bit. If you want objects of your class to be cloned, you must re-implement the clone() method in your class. Once you re-implement the clone() method, you should be able to clone objects of your class by calling the clone() method. The declaration of the clone() method in the Object class is as follows:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">protected Object clone() throws CloneNotSupportedException</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>You need to observe few things about the declaration of the clone() method.</b></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">It is declared <span style="color: blue;">protected</span>. Therefore, you will not be able to call it from the client code. The following code is not valid:</span><span style="font-family: Trebuchet MS, sans-serif;">Object obj = new Object();</span><span style="font-family: 'Trebuchet MS', sans-serif;">Object clone = obj.clone(); // <span style="color: red;">Error</span>. <span style="color: red;">Cannot access protected clone() method.</span></span><span style="font-family: 'Trebuchet MS', sans-serif;">This means you need to <span style="color: blue;">declare the clone() method public</span> in your class if you want the client code to clone objects of your class.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Its <span style="color: blue;">return </span>type is <span style="color: blue;">Object</span>. It means you will need to cast the returned value of the clone() method. Suppose MyClass is Cloneable. Your cloning code will look as<br />MyClass mc = new MyClass();<br />MyClass clone = (MyClass)mc.clone(); // Need to use a cast</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">You do not need to know any internal details about an object to clone it. The clone() method in the Object class has all the code that is needed to clone an object. All you need is to call it from the clone() method of your class. It will make a <span style="color: blue;">bitwise copy of the original</span> object and return the reference of the copy.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The clone() method in the Object class throws a <span style="color: red;">CloneNotSupportedException </span>. It means when you call the clone() method of the Object class, you need to place the call in a <span style="color: blue;">try-catch block</span>, or re-throw the exception.You have the option not to throw a CloneNotSupportedException from the clone() method of your class</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The following snippet of code is placed inside the clone() method of your class, which calls the<span style="color: blue;"> clone()</span> method of the Object class using the <span style="color: blue;">super </span>keyword:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-62-sZWR-br4/VOjaOdXHdjI/AAAAAAAAJC4/KwJyqMxWucM/s1600/Clone_method_implementation_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-62-sZWR-br4/VOjaOdXHdjI/AAAAAAAAJC4/KwJyqMxWucM/s1600/Clone_method_implementation_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">One important thing that you must do is add an "<span style="color: blue;">implements Cloneable</span>" clause in your class declaration. Cloneable is an <span style="color: blue;"><a href="http://java-latte.blogspot.com/2014/01/everything-about-interface-in-java.html" target="_blank">interface </a></span>declared in the java.lang package.Otherwise, you will get a <span style="color: blue;">runtime error </span>when you call the clone() method on the objects of your class.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-6oLC5Zfy3XM/VOjaun-7iuI/AAAAAAAAJDA/hGT8x18p1no/s1600/Burger_cloneable_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-6oLC5Zfy3XM/VOjaun-7iuI/AAAAAAAAJDA/hGT8x18p1no/s1600/Burger_cloneable_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Once your class implements the clone() method correctly, cloning an object of your class is as simple as calling its clone() method</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-JrXloR9k9Vs/VOja4gNyrCI/AAAAAAAAJDI/89AWRangRJ0/s1600/Clone_burger_class_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-JrXloR9k9Vs/VOja4gNyrCI/AAAAAAAAJDI/89AWRangRJ0/s1600/Clone_burger_class_in_java_latte.png" /></a></div>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">At this point, there are two separate objects of the Burger class. The <span style="color: blue;">veg </span>variable references the <span style="color: blue;">original object</span> and <span style="color: blue;">vegClone </span>variable references the clone of the original object. The original as well as the cloned object hold the same value of 100. However, they have separate copies of the value. If you change the value in the original object, for example, vegClone.setBurgerPrice(200), the value in the cloned object remains unchanged. Let see the tester class</span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-s6uGKQl6684/VOjbL41r8bI/AAAAAAAAJDQ/ELIyjNL-Opc/s1600/Burger_cloneable_demo_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-s6uGKQl6684/VOjbL41r8bI/AAAAAAAAJDQ/ELIyjNL-Opc/s1600/Burger_cloneable_demo_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>From Java 5</b>, you need not specify the return type of the clone() method in your class as the Object type. You can specify your class as the return type in the clone() method declaration. This will not force the client code to use a cast when it call the clone() method of your class.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-s0zLfsQM7Do/VOjbWH6mnbI/AAAAAAAAJDY/eVYnNNWKYjQ/s1600/Clone_method_after_java_5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-s0zLfsQM7Do/VOjbWH6mnbI/AAAAAAAAJDY/eVYnNNWKYjQ/s1600/Clone_method_after_java_5.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">With the above declaration for the clone() method, you can write code to clone an object as follows. Note that no cast is needed anymore</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-_ti_m3FUV5g/VOjbdywLuZI/AAAAAAAAJDg/ATiyOqszmEQ/s1600/Clone_method_after_java_5_demo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-_ti_m3FUV5g/VOjbdywLuZI/AAAAAAAAJDg/ATiyOqszmEQ/s1600/Clone_method_after_java_5_demo.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="font-size: large;">The standard pattern for making a class cloneable is:</span></span><br />
<ol style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Implement Cloneable</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Override the clone() method and make it public</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">In clone() call super.clone() and then copy any mutable object's state</span></li>
</ol>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">You should <span style="color: blue;">not create</span> a new object <span style="color: blue;">using new</span>. The <span style="color: blue;">proper way</span> is to call <span style="color: blue;">super.clone()</span> for a new instance. Object's clone() is special and will create a new copy of the object and copy its primitive fields and references.</span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Shallow Cloning</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">An <span style="color: blue;">object </span>may be <span style="color: blue;">composed of another objec</span>t. In such cases, two objects exist in memory separately—a <b>contained </b>object and a <b>container </b>object. The container object stores the reference of the contained object. When you clone the container object, the reference of the contained object is cloned. After cloning is performed, there are two copies of the container object; both of them have references to the same contained object. This is called <span style="color: blue;"><b>a shallow cloning</b></span> because <span style="color: blue;">references are copied, not the objects</span>. The clone() method of the Object class makes only shallow cloning, unless you code it otherwise.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-c-Sp-IWDl5w/VOjb6wcE-JI/AAAAAAAAJDo/zfa1KbU2XqM/s1600/Shallow_copy_in_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-c-Sp-IWDl5w/VOjb6wcE-JI/AAAAAAAAJDo/zfa1KbU2XqM/s1600/Shallow_copy_in_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b> ShallowClone </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-3EBDU3gXTig/VOjcNBlPS8I/AAAAAAAAJDw/sNWryjPWvpg/s1600/ShallowClone_class_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-3EBDU3gXTig/VOjcNBlPS8I/AAAAAAAAJDw/sNWryjPWvpg/s1600/ShallowClone_class_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">An object of the ShallowClone class is composed of an object of the <span style="color: blue;">Burger </span>class. The code in the <span style="color: blue;">clone() method of the ShallowClone</span> class is the same as for the <span style="color: blue;">clone() method of the Burger class</span>. The difference lies in the type of instance variables that are used for the two classes. The Burger class has an instance variable of primitive type int, whereas the ShallowClone class has an instance variable of the <span style="color: blue;">reference type</span> DoubleHolder. When the ShallowClone class calls the clone() method of the Object class (using super.clone()), it receives a shallow copy of itself. That is, it shares the Burger object used in its instance variable with its clone.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Following code test an object of the ShallowClone class and its clone. The output shows that a<span style="color: blue;">fter you make a clone, changing the value through the original object also changes the value in the cloned object</span>. This is so because the ShallowClone object stores the value in another object of the Burger class, which is shared by both the cloned and the original objects.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-7MjCdnHA8YE/VOjczDfvgNI/AAAAAAAAJD8/huORZacAZog/s1600/Shallow_copy_demo_in_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-7MjCdnHA8YE/VOjczDfvgNI/AAAAAAAAJD8/huORZacAZog/s1600/Shallow_copy_demo_in_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Deep Cloning</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When the contained objects are <span style="color: blue;">copied rather than their references</span> during cloning of a compound object, it is called <b><span style="color: blue;">deep cloning</span></b>. You must clone all the objects referenced by all reference variables of an object to get a deep cloning.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A compound object may have <span style="color: blue;">multiple levels of chaining</span> of contained objects. For example, the <span style="color: blue;">container </span>object may have a <span style="color: blue;">reference of another</span> contained object, which in turn has a <span style="color: blue;">reference of another contained</span> object and so on. Whether you will be able to perform a deep cloning of a compound object depends on many factors. If you have a reference of a contained object, <span style="color: blue;">it may not support cloning</span> and in that case, you have to be <span style="color: blue;">content with shallow cloning</span>. You may have a reference of a contained object, which itself is a compound object. However, the contained object supports only shallow cloning, and in that case again, you will have to be content with shallow cloning.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In a deep cloning, you need to <span style="color: blue;">clone all objects referenced by all reference</span> instance variables of an object. You must <b>perform a shallow cloning before you can perform a deep cloning</b>. The shallow cloning is performed by calling the clone() method of the Object class. Then you will need to write code to clone all reference instance variables.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b> DeepClone </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-e-z1WJFmyVo/VOjdpmkoobI/AAAAAAAAJEI/bL2VhJBPuwc/s1600/DeepClone_class_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-e-z1WJFmyVo/VOjdpmkoobI/AAAAAAAAJEI/bL2VhJBPuwc/s1600/DeepClone_class_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">If you <span style="color: blue;">compare</span> the code in the clone() method of the ShallowClone and DeepClone classes, you will find that for deep cloning you had to write only one extra line of code.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">copy.burger = (Burger)this.burger.clone();</span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif;">What will happen if the <span style="color: red;">Burger class is not cleanable</span>? In that case, you would not be able to write the above statement to clone the holder instance variable. You could have cloned the burger instance variable as follows:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">copy.burger = new Burger(this.burger.getValue());</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The goal is to clone the burger instance variable and it does not have to be done by calling its clone() method</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-2LQ1UEPSORM/VOjeC6UA4FI/AAAAAAAAJEQ/Z8TghOoVNAs/s1600/DeepClone_class_demo_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-2LQ1UEPSORM/VOjeC6UA4FI/AAAAAAAAJEQ/Z8TghOoVNAs/s1600/DeepClone_class_demo_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="font-size: large;">Clone Method</span></b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In order for implementing the Cloneable interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable, and largely undocumented protocol. It creates an object without calling a constructor. The general contract for the clone method is weak. Here it is, copied from the <span style="color: blue;">specification for java.lang.Object</span>:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-afh3RQxeAvc/VOlkph_OPEI/AAAAAAAAJEw/e1CEcspFCgQ/s1600/Clone_method_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-afh3RQxeAvc/VOlkph_OPEI/AAAAAAAAJEw/e1CEcspFCgQ/s1600/Clone_method_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>Tip</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Using the clone() method of the Object class is not the only way to make a clone of an object. You can use other methods to clone an object. You may provide a copy constructor, which accepts an object of the same class and creates a clone of that object. You may provide a factory method in your class, which may accept an object and returns its clone. Another way to clone an object is to serialize it and then deserialized it.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>The copy constructor approach and its static factory variant have many advantages over Cloneable/clone:</b></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">They do not rely on a risk-prone extralinguistic object creation mechanism Where as in clonealbe, In order for implementing the Cloneable interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable, and largely undocumented protocol. The resulting mechanism is extralinguistic: It creates an object without calling a constructor.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">They do not conflict with the proper use of final fields where in cloneable, If a class is not final, `clone` has to return the most derived class for which it was called. That can't work with a constructor, because `clone` doesn't know which one to call. If a class is final, it can't have any subclasses, so there's no danger in calling its constructor when cloning.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">They do not require the client to catch an unnecessary checked exception, where it require clonealbe require the client to handle the exception.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">They provide a statically typed object to the client.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning </span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">java</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">, why not help them out! Just share this post with them. Thanks for studying today!...</span>
</div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com5tag:blogger.com,1999:blog-5855689509747625696.post-47527215441261324292015-02-05T22:18:00.002+05:302015-02-05T22:18:15.587+05:30Assertions in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">When creating application programs, you assume many things. However, often it happens that the assumptions don’t hold, resulting in an erroneous condition. The <b>assert</b> statement is used to check or test your assumptions about the program. In this article, we try to understand how and when to use assert keyword in Java.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-7u9S-Z93W2w/VNOY8AkB_bI/AAAAAAAAI_4/y8_LBrJ0BO8/s1600/Assertion_example_main_image.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-7u9S-Z93W2w/VNOY8AkB_bI/AAAAAAAAI_4/y8_LBrJ0BO8/s1600/Assertion_example_main_image.png" height="174" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">There are many reasons <span style="color: blue;">why you should add assertions</span> to the program. One reason is that it helps find the problems early; when you check your assumptions in the program, and when any of them fail, you immediately know where to look out for the problem and what to fix. Also, when other programmers read your code with assertions, they will be in a better position to understand the code because you are making your <span style="color: blue;">assumptions explicit using assertions</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">keyword <b>assert</b> </span>provides support for assertions in Java. Each assertion statement contains a <span style="color: blue;">Boolean expression</span>. </span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: 'Trebuchet MS', sans-serif;">If the result of the Boolean expression is true, it means the assumption is true, nothing happens. </span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">However, if the Boolean result is false, then the assumption you had about the program holds no more, and an AssertionError is thrown. </span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">Remember that the Error class and its derived classes indicate <span style="color: blue;">serious runtime errors</span> and are not meant to be handled. In the same way, if an AssertionError is thrown, the best course of action is <span style="color: blue;">not to catch</span> the exception and to allow the program to terminate. After that, you need to examine why the assumption did not hold true and then fix the program.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">A simple assertion is a statement of the form:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><i>assert logical_expression;</i></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Here, <span style="color: blue;">assert</span> is a keyword, and <span style="color: blue;">logical_expression</span> is any expression that results in a value of true or false . When this statement executes, if logical_expression evaluates to true , then the program continues normally. If logical_expression evaluates to false , the program is terminated with an error </span><span style="font-family: 'Trebuchet MS', sans-serif;">message starting with: <span style="color: red;">java.lang.AssertionError. T</span></span><span style="font-family: Trebuchet MS, sans-serif;">his is followed by more information about where the error occurred in the code. When this occurs, the program is said to assert.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Assert Statement</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Assert statements in Java are of two forms:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="color: blue; font-family: Trebuchet MS, sans-serif;">assert booleanExpression;</span></li>
<li><span style="color: blue; font-family: Trebuchet MS, sans-serif;">assert booleanExpression : "Detailed error message string";</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">It is a compiler error if a non-Boolean expression is used within the assert statement.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In this program, you are checking if the value of i is < 0; you are using the expression –i to convert it to a positive value. Once the condition check if (i < 0) is completed, the value of i cannot be negative, or that is your assumption. Such assumptions can be asserted with an assert statement.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The program will run fine if the Boolean expression (i >= 0) evaluates to true. However, if it evaluates to false, the program will crash by throwing an AssertionError.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-yUPJNAMJ0n8/VNOWEnLWsAI/AAAAAAAAI_I/NiO3ifksB3g/s1600/assertions_example_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-yUPJNAMJ0n8/VNOWEnLWsAI/AAAAAAAAI_I/NiO3ifksB3g/s1600/assertions_example_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Output:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-dHGPKpJR0SA/VNOWPhsiZCI/AAAAAAAAI_Q/EdzARx9t3PI/s1600/assertions_example_output_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-dHGPKpJR0SA/VNOWPhsiZCI/AAAAAAAAI_Q/EdzARx9t3PI/s1600/assertions_example_output_java_latte.png" height="63" width="400" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Yes, this program executed successfully without throwing any exceptions.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: red;">Is there any value of i for which the condition will fail?</span> <b>Yes</b>, there is! If the value of i is a minimum possible value of integer, then it cannot be converted into a positive value. Why? Remember that the range of integers is -2^31 to 2^31 – 1, so the integer values the value of i as –2147483648 to 2147483647. In other words, the positive value 2147483648 is not in the range of integers. So, if the value of i is –2147483648, then the expression -i will overflow and again result in the value –2147483648. Thus, your assumption is not true.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">int i = Integer.MIN_VALUE;</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Output</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-LwWlKcYxiyY/VNOWeYURMzI/AAAAAAAAI_Y/lCvo61Kepi8/s1600/assertions_example_output_fail_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-LwWlKcYxiyY/VNOWeYURMzI/AAAAAAAAI_Y/lCvo61Kepi8/s1600/assertions_example_output_fail_java_latte.png" height="96" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Enable/Disable Assertion</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-nwIeEmQPxaA/VNOXQAJUHaI/AAAAAAAAI_k/tx-1ohaLxW4/s1600/How%2Bto%2B%2Benable%2BAssertions_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-nwIeEmQPxaA/VNOXQAJUHaI/AAAAAAAAI_k/tx-1ohaLxW4/s1600/How%2Bto%2B%2Benable%2BAssertions_in_java_latte.png" height="190" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">You saw that assertions are disabled at runtime; to enable assertions at runtime, use an <span style="color: blue;">-ea</span> switch.To disable assertions at runtime, use a <span style="color: blue;">-da</span> switch. If assertions are disabled by default at runtime, then what is the use of -da switch? There are many uses. For example, if you want to enable assertions for all classes within a given package and want to disable asserts in a specific class in that package, then a -da switch is useful.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-xxQCQDQRjkk/VNOXjw0pHSI/AAAAAAAAI_s/tUSWoRbum88/s1600/assertions_command_line_arguments_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-xxQCQDQRjkk/VNOXjw0pHSI/AAAAAAAAI_s/tUSWoRbum88/s1600/assertions_command_line_arguments_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>How Not to Use Asserts</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The key to understanding assertions is that they are useful for debugging and testing applications, and assertions are meant to be disabled when the application is deployed to end users.</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Don’t use assertions for validating input values or for validating arguments to <span style="color: blue;">public methods</span>. For signaling such runtime failures, use exceptions instead.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Don’t use assertions to check conditions that are required for the <span style="color: blue;">correct functioning of the application.</span> Since assertions are disabled by default at runtime, the application will not function correctly when the asserted conditions are not present in the code.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">The Boolean expressions given inside assert statements <span style="color: blue;">should not have side effects</span>— modifying variable values, printing values to console, etc. In other words, the functioning of the application should remain the same no matter if assertions are enabled or disabled.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span><br />
<br /></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com4tag:blogger.com,1999:blog-5855689509747625696.post-83742246694229802852014-12-26T10:58:00.001+05:302014-12-26T10:58:56.450+05:30String pool concept in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;"><a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">String</a> pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. This is the most basic and predominant concept that every Java developer should know. In this article, we understand the concept of pooling with the help of few examples.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-4zaj1okadis/VJzvTKPqxII/AAAAAAAAI5s/9YHLw2FkT4w/s1600/String_pool_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-4zaj1okadis/VJzvTKPqxII/AAAAAAAAI5s/9YHLw2FkT4w/s1600/String_pool_java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>You can create objects</b> of the class <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">String</a> by using the <span style="color: blue;">new operato</span>r, by using the <span style="color: blue;">assignment operator</span> ( = ), or by enclosing a value within <span style="color: blue;">double quotes</span> ( " ). But you may have noticed a big difference in how these objects are created, stored, and referred by Java.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Let’s create two <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">String</a> objects with the value "JavaLatte" using the operator new :</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-nas4t4KFPGY/VJvPz4oIVGI/AAAAAAAAI4E/mzYmhQ-qgaI/s1600/String_using_new_keyword_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-nas4t4KFPGY/VJvPz4oIVGI/AAAAAAAAI4E/mzYmhQ-qgaI/s1600/String_using_new_keyword_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">This image illustrates the previous code.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-3ur2GWmPkUs/VJvPxXZiyFI/AAAAAAAAI30/TRLrcuEa24k/s1600/String_using_new_keyword_explanatation_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-3ur2GWmPkUs/VJvPxXZiyFI/AAAAAAAAI30/TRLrcuEa24k/s1600/String_using_new_keyword_explanatation_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In the previous code, a comparison of the String <a href="http://java-latte.blogspot.in/2014/09/difference-between-object-reference-variables-primitive-variables-in-java.html" target="_blank">reference</a> variables str1 and str2 prints <span style="color: blue;">false</span> . The operator<span style="color: blue;"> ==</span> <span style="color: blue;">compares the addresses </span>of the objects referred to by the variables str1 and str2 . Even though these String objects store the same sequence of characters, they refer to separate objects that are <span style="color: blue;">stored at separate locations.</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Let’s create two <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">String</a> objects with the value "Latte" using the assignment operator ( = ). </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-avt6PC08e90/VJvP0q1TyqI/AAAAAAAAI4I/hLRZ5CuqDIo/s1600/String_using_quotes_keyword_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-avt6PC08e90/VJvP0q1TyqI/AAAAAAAAI4I/hLRZ5CuqDIo/s1600/String_using_quotes_keyword_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">The variables str3 and str4 and the objects referred to by these variables</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-HTe1BM_sbdQ/VJvP0KgxhnI/AAAAAAAAI4Q/1kR8S0lh6mo/s1600/String_using_quotes_keyword_explanation_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-HTe1BM_sbdQ/VJvP0KgxhnI/AAAAAAAAI4Q/1kR8S0lh6mo/s1600/String_using_quotes_keyword_explanation_java_latte.png" height="275" width="320" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">In the previous example, the variables str1 and str2 <span style="color: blue;">referred to different String</span> objects, even if they were created using the same sequence of characters. In the case of variables str3 and str4, the objects are <span style="color: blue;">created and stored in a <b>pool</b></span> of String objects. Before creating a new object in the pool, Java first searches for an object with similar contents.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">When the following line of code executes, no String object with the value "Latte" is found in the pool of String objects:</span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">String str3 = "Latte";</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">As a result, Java creates a String object with the value "Latte" in the pool of String objects referred to by variable str3. See the image for understanding this</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-j82D62GwV98/VJvPyhyubTI/AAAAAAAAI4A/Ga0GKM-O0Ao/s1600/String_pool_explanation_one_Java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-j82D62GwV98/VJvPyhyubTI/AAAAAAAAI4A/Ga0GKM-O0Ao/s1600/String_pool_explanation_one_Java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">When the following line of code executes, Java is able to find a String object with the value "Latte" in the pool of String objects:</span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">String str4 = "Latte";</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-jPPAyI1SIhM/VJvPyk_TOtI/AAAAAAAAI38/C4_DpDL5m5s/s1600/String_pool_explanation_two_Java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-jPPAyI1SIhM/VJvPyk_TOtI/AAAAAAAAI38/C4_DpDL5m5s/s1600/String_pool_explanation_two_Java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Java doesn’t create a new String object in this case, and the variable str4 refers to the existing String object "Latte".</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">You can also create a String object by enclosing a value within <span style="color: blue;">double quotes</span> ( " ):</span><br />
<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>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-iHmK5knKCSU/VJvShJL7-uI/AAAAAAAAI5A/dWKtMsFulLc/s1600/String_with_quotes_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-iHmK5knKCSU/VJvShJL7-uI/AAAAAAAAI5A/dWKtMsFulLc/s1600/String_with_quotes_java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">These values are reused from the String constant pool if a matching value is found. If a matching value isn’t found, the JVM creates a String object with the specified value and places it in the String constant pool:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-g_JdU4A7bP8/VJvSqnUzdLI/AAAAAAAAI5I/PIaXzkYCTeM/s1600/String_with_quotes_1_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-g_JdU4A7bP8/VJvSqnUzdLI/AAAAAAAAI5I/PIaXzkYCTeM/s1600/String_with_quotes_1_java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Compare the preceding example with the following example, which creates a String object using the operator new and (only) double quotes and then compares their references:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-WVHaWjUE6OE/VJvSq-b_ZLI/AAAAAAAAI5M/b81iYbCi8Yk/s1600/String_with_quotes_2_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-WVHaWjUE6OE/VJvSq-b_ZLI/AAAAAAAAI5M/b81iYbCi8Yk/s1600/String_with_quotes_2_java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The preceding code shows that object references of String objects that exist in the String constant pool and object references of String objects that <span style="color: blue;">don’t exist in the String constant pool don’t refer to the same String object</span>, even if they <span style="color: blue;">define the same String value</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Where String pool is stored in memory</b></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>Java 6</b><br /><a href="http://java-latte.blogspot.in/2013/08/garbage-collection-in-java.html" target="_blank">Permanent Generation</a> part of the heap structure - the fixed size part of heap mainly used for storing loaded classes and string pool. Note that the permanent generation is not part of the heap. It's a separate space for class definitions and related data, as well as where interned strings live<br /><br /><div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/--HbsesdcCh4/VJvUyekAAnI/AAAAAAAAI5c/-M3jmO0VJiw/s1600/heap_generation.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/--HbsesdcCh4/VJvUyekAAnI/AAAAAAAAI5c/-M3jmO0VJiw/s1600/heap_generation.PNG" height="300" width="400" /></a></div>
</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>Java 7</b><br />The <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">string</a> pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">strings</a> are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">Note strings in the JVM string pool are eligible for <a href="http://java-latte.blogspot.in/2013/08/garbage-collection-in-java.html" target="_blank">garbage collection</a> if there are no references to them from your program roots. It means that if your interned <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">string</a> went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.</span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="font-size: large;">Use of String <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">intern</a>() method</span></b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Returns a canonical representation for the string object.</span>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the <span style="color: blue;">pool</span> already contains a string equal to this String object as <span style="color: blue;">determined</span> by the <span style="color: blue;">equals(Object)</span> method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">It follows that for any two strings s and t, <span style="color: blue;">s.intern() == t.intern()</span> is true if and only if<span style="color: blue;"> s.equals(t) is true</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">All literal strings and string-valued constant expressions are <a href="http://java-latte.blogspot.in/2012/11/why-string-is-immutable.html" target="_blank">interned</a>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">String allocation, like any other object creation proves <span style="color: blue;">costly in time and memory.</span>The JVM do some trickery while instantiating the string literals to <span style="color: blue;">increase</span> <span style="color: blue;">performance</span> and <span style="color: blue;">decrease</span> <span style="color: blue;">memory</span> overhead. To decease the number of creation of String object in JVM, the String class keeps a pool of Strings. Each time you create a string literal, the JVM checks the string literal pool first. If a string is found in the pool, a reference to the pooled string is return.if the String is not exist in the pool, a new string object is instantiates, then placed in the pool.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com4tag:blogger.com,1999:blog-5855689509747625696.post-22836230627607509062014-12-22T13:53:00.000+05:302014-12-22T13:53:31.231+05:30ClassCastException in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">ClassCastException exception is thrown when an attempt is made to cast between incompatible types (such as String to Integer type or vice versa). In this article, we understand this exception in more detail and find out the way to avoid this exception with examples.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-vzEhIgP2ALg/VJfT8iXieeI/AAAAAAAAI2I/EWhKn44NwzA/s1600/classCastException_hierarchy_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-vzEhIgP2ALg/VJfT8iXieeI/AAAAAAAAI2I/EWhKn44NwzA/s1600/classCastException_hierarchy_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="font-size: large;">ClassCastException</span></b> </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:</span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">Object x = new Integer(0);</span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">System.out.println((String)x);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Take a look at the above figure to review the class hierarchy of this exception. Examine the code where the line of code that throws the ClassCastException is shown in bold.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-YYIw78tJzg0/VJfSQ0CdliI/AAAAAAAAI1Y/7tnlMYq_s5Q/s1600/classCastException_Java_example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-YYIw78tJzg0/VJfSQ0CdliI/AAAAAAAAI1Y/7tnlMYq_s5Q/s1600/classCastException_Java_example.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>ClassCastException</b> <span style="color: blue;">is thrown when</span> an object fails an IS-A test with the class type to which it’s being cast. In the preceding example, class Ink is the base class for classes ColorInk and BlackInk. The JVM throws a ClassCastException in the previous case because the line of code in bold<span style="color: blue;"> tries to explicitly cast </span>an object of ColorInk to BlackInk.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Why above code avoided the compilation error</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Note that above line of code avoided the compilation error because the variable inks defines an ArrayList of type Ink , which is <span style="color: blue;">capable of storing objects of type Ink</span> and all its <span style="color: blue;">subclasses</span>. The code then correctly adds the allowed objects: one each of BlackInk and ColorInk.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">If the code had defined an ArrayList of type BlackInk or ColorInk , the code would have failed the compilation, as follows:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-GkCgy9WQte4/VJfSy6AnXgI/AAAAAAAAI1g/YQ19MU6Hgio/s1600/classCastException_compilation_error_Java_example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-GkCgy9WQte4/VJfSy6AnXgI/AAAAAAAAI1g/YQ19MU6Hgio/s1600/classCastException_compilation_error_Java_example.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Here’s the compilation error thrown by the previously modified piece of code:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-uKmf8Udu0VM/VJfS5FsDEaI/AAAAAAAAI1o/E_zKUfaVD7w/s1600/classCastException_compilation_error_Java_example_output.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-uKmf8Udu0VM/VJfS5FsDEaI/AAAAAAAAI1o/E_zKUfaVD7w/s1600/classCastException_compilation_error_Java_example_output.png" height="126" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>How to avoid ClassCastException</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">If a ClassCastException is thrown while executing a program, and if there are no exception handlers for that, the program will terminate. So, how about providing an exception handler like this?</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-zGRwipfuwlQ/VJfTOo6eNpI/AAAAAAAAI1w/uX5tDbY6vk8/s1600/wrong_way_to_avoid_classCastException.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-zGRwipfuwlQ/VJfTOo6eNpI/AAAAAAAAI1w/uX5tDbY6vk8/s1600/wrong_way_to_avoid_classCastException.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">Yes, this will work and the program will not crash. But this is a really bad idea! There are <span style="color: blue;">two main problems in this code</span>.</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Providing exception handlers for RuntimeExceptions like this create an illusion that the program is working perfectly fine, when it is not!</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Runtime exceptions like ClassCastException indicate programming errors and should not be caught using exception handlers.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">Okay, so what do you do now? Before downcasting, <span style="color: blue;">check for the dynamic type</span> of the object and then downcast. You can use the <b><span style="color: blue;">instanceof</span></b> operator to verify whether an object can be cast to another class before casting it.</span></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-Vi0woz_yECU/VJfTdZGc06I/AAAAAAAAI14/74azlilTeUU/s1600/right_way_to_avoid_classCastException.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-Vi0woz_yECU/VJfTdZGc06I/AAAAAAAAI14/74azlilTeUU/s1600/right_way_to_avoid_classCastException.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">This is an effective and proper way to achieve downcasting. Using the <b><span style="color: blue;">instanceof</span></b> operator checks the dynamic type of obj, which helps you to decide whether to downcast it to a String object.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Continue with our main example. Assuming that the definition of classes Ink , ColorInk, and BlackInk are the same as defined in the previous example, the <span style="color: blue;">following lines of code will avoid the ClassCastException</span></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-j9T0v5Ksqh8/VJfTpyLZdBI/AAAAAAAAI2A/j5SacUqSbYk/s1600/Avoid_classCastException_java_example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-j9T0v5Ksqh8/VJfTpyLZdBI/AAAAAAAAI2A/j5SacUqSbYk/s1600/Avoid_classCastException_java_example.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In the previous example, the condition <span style="color: blue;">( inks.get(0)instanceofBlackInk )</span> evaluates to false , so the then part of the if statement doesn’t execute.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Question</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Try to examine and share the output of the following program in comment section</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-plCa0eEr6oI/VJfUljb8KFI/AAAAAAAAI2U/JXa_p7wPX6U/s1600/ClassCastException_objective_question.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-plCa0eEr6oI/VJfUljb8KFI/AAAAAAAAI2U/JXa_p7wPX6U/s1600/ClassCastException_objective_question.png" /></a></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"> with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com0tag:blogger.com,1999:blog-5855689509747625696.post-17295318939537672642014-11-23T00:50:00.001+05:302014-11-23T00:50:06.806+05:30Finding superclasses of an object in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we look into one of the mechanism of an Reflection to find about the super classes of any object in Java with example. Reflection </span><span style="font-family: 'Trebuchet MS', sans-serif;">enables what is commonly referred to as dynamic pro</span><span style="font-family: 'Trebuchet MS', sans-serif;">gramming in Java. Reflection in Java is accomplished </span><span style="font-family: 'Trebuchet MS', sans-serif;">using the Java Reflection API</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-2DnA_7vlSW8/VHDhnC9dM-I/AAAAAAAAIu0/sVEX6O55h6M/s1600/find_super_class_of_an_object_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-2DnA_7vlSW8/VHDhnC9dM-I/AAAAAAAAIu0/sVEX6O55h6M/s1600/find_super_class_of_an_object_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue;">Reflection</span></b> is a mechanism for discovering data about a program at run-time. The most basic thing you usually do when doing reflective programming is to get a Class object. Once you have a Class object instance, you can obtain all sorts of information about the class and even manipulate the class.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Finding Superclasses</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">ancestors</span> of a given class are referred to as that class’s <b>superclasses</b>. Using reflection, you can determine all of the ancestors of a given class. After you've obtained a Class object, you can use the<span style="color: blue;"> getSuperclass()</span> method to get the class’s superclass if one exists. If a superclass exists, a Class object will be returned. If there is not a superclass, this method will return null. Remember that <span style="color: blue;"><a href="http://java-latte.blogspot.in/2012/11/why-java-does-not-support-multiple.html" target="_blank">Java supports only single inheritance</a></span>, so for any given class, there can be only one superclass. Actually to be clear, there can be only one direct superclass.<b>Technically</b>, all ancestor classes are considered to be superclasses of a given class.To retrieve all ancestor superclasses, you would recursively call the getSuperclass() method on each Class object that is returned.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Here is an example, that explain the above concept </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-_zxIEH59JVM/VHDgZbNrtYI/AAAAAAAAIuc/d9IPW2gkx0g/s1600/Reflection_example_in_Java_A_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-_zxIEH59JVM/VHDgZbNrtYI/AAAAAAAAIuc/d9IPW2gkx0g/s1600/Reflection_example_in_Java_A_class.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-1u93iJxztYY/VHDgZVW8vbI/AAAAAAAAIuY/kZWAPzuKfBU/s1600/Reflection_class_example_demo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-1u93iJxztYY/VHDgZVW8vbI/AAAAAAAAIuY/kZWAPzuKfBU/s1600/Reflection_class_example_demo.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example 2 </b>In this example, we try to find the super classes of BigDecimal class. </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-Tkz6yeKxsXc/VHDg7tXmAjI/AAAAAAAAIus/tuFHyZysdPw/s1600/Reflection_class_demo_of_java_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-Tkz6yeKxsXc/VHDg7tXmAjI/AAAAAAAAIus/tuFHyZysdPw/s1600/Reflection_class_demo_of_java_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"> with them. Thanks for studying today!...</span><br />
<br /></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-6470340305946954142014-11-01T14:40:00.000+05:302014-11-01T14:40:11.531+05:30Implicit Objects In JSP<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;"><b>JavaServer Pages</b> (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. In this article, we look into the <span style="color: blue;">9 implicit objec</span>t of JSP with explanation and examples.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-lP5laFiOfFc/VFSikorH-zI/AAAAAAAAIq4/GBaMMBynYkc/s1600/jsp_implicit_objects.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-lP5laFiOfFc/VFSikorH-zI/AAAAAAAAIq4/GBaMMBynYkc/s1600/jsp_implicit_objects.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In a web application, multiple web components collaborate with each other and share information by means of objects that are maintained as <span style="color: blue;">attributes of four scope</span> objects. You access these attributes by using the <span style="color: blue;">getAttribute </span>and <span style="color: blue;">setAttribute </span>methods of the class representing the scope</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-FmnAblf3nqQ/VFSeuEFRbAI/AAAAAAAAIqk/XO7rSrsSPFE/s1600/JSP_scope_objects_in_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-FmnAblf3nqQ/VFSeuEFRbAI/AAAAAAAAIqk/XO7rSrsSPFE/s1600/JSP_scope_objects_in_java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Note </b>In addition to the standard servlet request, session, and application scopes, JSP adds a fourth scope called page scope.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A JSP page can access some specific objects through scripting variables. These objects are provided by the JSP container and are called <b>implicit objects</b>. These implicit objects can be accessed in <span style="color: blue;">scriptlets</span>, in <span style="color: blue;">expressions</span>, or as part of the <span style="color: blue;">EL expressions</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-J9j0l_FviDE/VFSe__kXS-I/AAAAAAAAIqs/cYgEj2uJZNU/s1600/JSP_implicit_objects_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-J9j0l_FviDE/VFSe__kXS-I/AAAAAAAAIqs/cYgEj2uJZNU/s1600/JSP_implicit_objects_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">application</span></b><br />The implicit application object provides a reference to the <span style="color: blue;">javax.servlet.ServletContext</span> interface. The <span style="color: blue;">ServletContext </span>interface is used to provide access to any context-initialization parameters that have been configured for the JSP page via the deployment descriptor of the web application. The ServletContext object and parameters stored in them by the web container are available to the entire web application. The application object provides the developer of the JSP page with access to the ServletContext object.<br /><b>In short</b>, application provides access to web context. Its use is similar to that of ServletContext.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">config</span></b><br />Similar to the application object, the config object provides a reference to the <span style="color: blue;">ServletConfig </span>interface of the web application. The ServletConfig interface is used to provide access to any initialization parameters that have been configured for the JSP page via the deployment descriptor of the web application. The config object provides the JSP developer with access to the ServletConfig object.<br /><b>In short</b>, config provides initialization information used by the JSP container. Its use is similar to that of the class ServletConfig.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">exception</span></b><br />The implicit exception object is available to JSP to handle the error conditions and report the <span style="color: blue;">runtime exceptions</span> using the <span style="color: blue;">errorPage page</span> directive. Exception represents an instance of the Throwable object and contains error information. This variable is available only from the JSP error page<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">out</span></b><br />The implicit out object represents an instance of the <span style="color: blue;">JspWriter </span>class that is used to write character data to the response stream. out represents the output write stream JspWriter. This variable points at the same object as <span style="color: blue;">HttpServletResponse.getWriter()</span> in servlets. For example, a simplest JSP that returns a result from a Java class called CurrencyConverter might look like this<br /><i><span style="color: blue;"><html><br /> <body><br /> <% out.println(CurrencyConverter.getDollarRate()); %><br /> </body><br /></html><br /></span></i></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">page</span></b><br />The JSP implicit page object is an instance of the Object class and represents the <span style="color: blue;">current JSP page</span>. In short, page represents the instance of the JSP’s servlet.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">pageContext</span></b><br />A pageContext provides context information by providing access to all the namespaces associated with a JSP page and to several page attributes. Also, it contains the reference to <span style="color: purple;">implicit objects</span>. pageContext represents the JSP context and is used with Tag Libraries<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">request</span></b><br />The request object is an instance of the <span style="color: blue;">javax.servlet.http.HttpServletRequest</span> interface. It represents the client request. The request implicit object is generally used to get request parameters, request attributes, header information, and query string values.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">response</span></b><br />The implicit response object is an instance of the <span style="color: blue;">javax.servlet.http.HttpServletResponse</span> interface and represents the response to be given to the client. The implicit response object is generally used to set the response content type, add cookies, and redirect the response.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue; font-size: large;">session</span></b><br />The JSP implicit session object is an instance of a Java class that implements the <span style="color: blue;">javax.servlet.http.HttpSession</span> interface. It is used to store session state for a client.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">Examples of Common Implicit Objects</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>getServletContext().setAttribute</b>("blog", JavaLatte);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in a ServletContext without using implicit objects.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>request.setAttribute(</b>"blog", JavaLatte);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in a request object. The request object is also an implicit object in JSP. Hence, setting the attribute in a servlet is similar to setting the attribute in a JSP page.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>request.getSession().setAttribute</b>("book", book);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in the session without using implicit objects</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>application.setAttribute</b>("book" book);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in the ServletContext using the application implicit object.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>request.setAttribute</b>("book" book);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in a request object. request is also an implicit object in JSP. Hence, setting the attribute in JSP is similar to setting the attribute in a servlet.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>session.setAttribute</b>("book" book);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in the session using a session implicit object</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><b>pageContext.setAttribute</b>("book" book);</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This sets the book attribute in PageContext using a pageContext implicit object. There is no equivalent of pageContext in a servlet. A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, and provides a layer above the implementation details. Implicit objects are added to the pageContext automatically.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"> with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com0tag:blogger.com,1999:blog-5855689509747625696.post-81171599273168221222014-10-25T13:58:00.001+05:302014-10-29T10:43:31.939+05:30 How Hibernate Works and it's Persistence Lifecycle<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">The main idea behind any <b>ORM</b> framework is to replace writing SQL with manipulating the objects. In the Java world, this means putting a layer on top of JDBC that will enable you to simply create a <b>POJO</b>, assign values to its fields, and tell it “<span style="color: blue;">Persist yourself in the database</span>.” This is what Hibernate is for. In this article, we look into overview of how hibernate works and its main components. By going through this, you'll able to answers about hibernate in an interview.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-H9llMnF_Dw8/VEtescc4m8I/AAAAAAAAIl8/yTiBFVkI704/s1600/How_hibernate_works_by_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-H9llMnF_Dw8/VEtescc4m8I/AAAAAAAAIl8/yTiBFVkI704/s1600/How_hibernate_works_by_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Hibernate's <span style="color: blue;">primary feature</span> is <span style="color: blue;">mapping </span>from <b>Java classe</b>s to <b>database tables</b> (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance overhead</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Hibernate architecture</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">As you can see from following picture, how much of Hibernate you use depends on your needs. At its <span style="color: blue;">simplest level</span> Hibernate provides a lightweight architecture that<span style="color: blue;"> deals only with <b>ORM</b></span>. Full-blown usage of Hibernate fully abstracts most aspects of persistence, such as transaction, entity/query caching, and connection pooling.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-uXCT4mqWNtw/VEtVDGUfSWI/AAAAAAAAIlM/MZW8Y8v8pg4/s1600/Hibernate_architecture_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-uXCT4mqWNtw/VEtVDGUfSWI/AAAAAAAAIlM/MZW8Y8v8pg4/s1600/Hibernate_architecture_in_java_latte.png" height="512" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>How Hibernate Works</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Hibernate’s success lies in the simplicity of its core concepts. At the <b>heart </b>of every interaction between your code and the database lies the <b><span style="color: blue;">Hibernate Session</span></b>. Following image provides an overview of how Hibernate works and don't need any explanation if you have an idea about hibernate.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-Wnwt9-_Kuuk/VEtVWsY0CRI/AAAAAAAAIlU/fX-tipttYX4/s1600/How_hibernate_works_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-Wnwt9-_Kuuk/VEtVWsY0CRI/AAAAAAAAIlU/fX-tipttYX4/s1600/How_hibernate_works_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The heart of any <b>Hibernate application</b> is in its configuration. There are two pieces of configuration required in any Hibernate application: one creates the database connections, and the other creates the object-to-table mapping</span><br />
<div>
<span style="font-family: Trebuchet MS, sans-serif;">Let's see the basic introduction to all the component and there roles in hibernate.</span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Configure the Database Connection (.cfg.xml)</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">To create a connection to the database, Hibernate must know the details of our database, tables, classes, and other mechanics. This information is ideally provided as an XML file (usually named<span style="color: blue;"> hibernate.cfg.xml</span>) or as a simple text file with name/value pairs (usually named <span style="color: blue;">hibernate.properties</span>).</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In XML style. We name this file hibernate.cfg.xml so the framework can load this file automatically.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The following snippet describes such a configuration file. Because I am using MySQL as the database, the connection details for the MySQL database are declared in this <span style="color: blue;">hibernate.cfg.xml</span> file:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-lhYd3c-nr64/VEtWyQ1frnI/AAAAAAAAIlg/VCpbSNkiarU/s1600/hibernage_conf_xml_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-lhYd3c-nr64/VEtWyQ1frnI/AAAAAAAAIlg/VCpbSNkiarU/s1600/hibernage_conf_xml_java_latte.png" height="377" width="400" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The preceding properties can also be expressed as name/value pairs. For example, here’s the same information represented as name/value pairs in a text file titled </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">hibernate.properties:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">hibernate.connection.driver_class = com.mysql.jdbc.Driver</span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">hibernate.connection.url = jdbc:mysql://localhost:3307/JH</span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">hibernate.dialect = org.hibernate.dialect.MySQL5Dialect</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>connection.url</b> indicates the URL to which we should be connected, <b>driver_class</b> represents the relevant Driver class to make a connection, and the <b>dialect </b>indicates which database dialect we are using (MySQL, in this case). If you are following the hibernate.properties file approach, note that all the properties are prefixed with “<span style="color: blue;">hibernate</span>” and follow a pattern—hibernate.* properties, for instance</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Beyond providing the configuration properties, we also have to provide mapping files and their locations. As mentioned earlier, a mapping file indicates the mapping of object properties to the row column values. This mapping is done in a separate file, usually suffixed with .hbm.xml. We must let Hibernate know our mapping definition files by including an element mapping property in the previous config file, as shown here:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div style="text-align: left;">
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"><hibernate-configuration></span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"> <session-factory></span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"> ...</span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"> <mapping resource="table1.hbm.xml" /></span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"> <mapping resource="table2.hbm.xml" /></span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"> <mapping resource="table3.hbm.xml" /></span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"> </session-factory></span><br />
<span style="color: blue; font-family: 'Trebuchet MS', sans-serif;"></hibernate-configuration></span></div>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Create Mapping Definitions</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Once we have the connection configuration ready, the next step is to prepare the table1.hbm.xml file consisting of object-table mapping definitions. The following XML snippet defines mapping for our Movie object against the TABLE1 table:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><hibernate-mapping></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> <class name="com.java.latte.table1" table="<b>TABLE1</b>"></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> <id name="id" column="ID"></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> <generator class="native"/></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> </id></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> <property name="title" column="TITLE"/></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> <property name="director" column="DIRECTOR"/></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> <property name="synopsis" column="SYNOPSIS"/></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"> </class></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"></hibernate-mapping></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">There is a lot going on in this mapping file. The hibernate-mapping element holds all the class-to-table mapping definitions. Individual mappings per object are declare under the class element. The name attribute of the class tag refers to our POJO domain class </span><span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">com.java.latte.table1</span><span style="font-family: Trebuchet MS, sans-serif;">, while the table attribute refers to the table TABLE1 to which the objects are persisted.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The remaining properties indicate the mapping from the object’s variables to the table’s columns (e.g., the id is mapped to ID, the title to TITLE, director to DIRECTOR, etc.). Each object must have a unique identifier—similar to a primary key on the table. We set this identifier by implementing the id tag using a native strategy.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>What does Hibernate do with this properties file?</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The Hibernate framework <span style="color: blue;">loads </span>this file to <span style="color: blue;">create a <b>SessionFactory</b></span>, which is thread-safe global factory class for creating Sessions. We should ideally create a single SessionFactory and share it across the application. Note that a SessionFactory is defined for one, and only one, database. For instance, if you have another database alongside MySQL, you should define the relevant configuration in <span style="color: blue;">hibernate.hbm.xml</span> to create a separate SessionFactory for that database too.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The goal of the <span style="color: blue;">SessionFactory is to create Session objects</span>. <b>Session </b>is a<span style="color: blue;"> gateway to our database</span>. It is the Session’s job to take care of all database operations such as <span style="color: blue;">saving</span>, <span style="color: blue;">loading</span>, and <span style="color: blue;">retrieving </span>records from relevant tables. The framework also maintains at transnational medium around our application. The operations involving the database access are wrapped up in a single unit of work called a transaction. So, all the operations in that transaction are either successful or rolled back.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Keep in mind that the configuration is used to create a Session via a SessionFactory instance. Before we move on, note that <span style="color: blue;">Session objects are <b>not thread-safe</b></span> and therefore should not be shared across different classes.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Hibernate Session</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The Hibernate Session <span style="color: blue;">embodies </span>the <span style="color: blue;">concept of a persistence service</span> (or persistence manager) that <span style="color: blue;">can be used</span> to query and perform <b>insert</b>, <b>update</b>, and <b>delete </b>operations on <span style="color: blue;">instances of a class mapped by Hibernate</span>. In an ORM tool you perform all of these interactions using object oriented semantics; that is, you <span style="color: blue;">no longer are referring to tables and columns</span>, but you use Java classes and object properties. As its name implies, the <b>Session </b>is a <span style="color: blue;">short-lived</span>, <span style="color: blue;">lightweight </span>object used as a <b>bridge </b>during a conversation between the <span style="color: blue;">application and the database</span>. The Session wraps the underlying JDBC connection or J2EE data source, and it serves as a first-level cache for persistent objects bound to it.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Session Factory</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Hibernate requires that you provide it with the information required to connect to each database being used by an application as well as which classes are mapped to a given database. Each one of these database-specific <span style="color: blue;">configuration files</span>, along with the associated <span style="color: blue;">class mappings</span>, are <span style="color: blue;">compiled </span>and <span style="color: blue;">cached </span><b>by the SessionFactory</b>, which is used to retrieve Hibernate Sessions. The SessionFactory is a <span style="color: blue;">heavyweight </span>object that should ideally be created only once (since it is </span><span style="font-family: 'Trebuchet MS', sans-serif;">an expensive and slow operation) and made available to the application code that needs to perform persistence operations</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Each SessionFactory is configured to work with a certain database platform by using one of the provided<b> Hibernate dialects</b>. The choice of Hibernate dialect is important when it comes to using databasespecific features like native primary key generation schemes or Session locking. At the time of this writing Hibernate (version 3.1) supports 22 database dialects. Each of the dialect implementations are in the package <span style="color: blue;">org.hibernate.dialect</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Hibernate Object Mappings</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Hibernate specifies <span style="color: blue;">how each object state</span> is <span style="color: blue;">retrieved </span>and <span style="color: blue;">stored </span>in the database via an XML configuration file. Hibernate mappings are l<span style="color: blue;">oaded at startup and are cached</span> in the <b>SessionFactory</b>. Each mapping specifies a variety of parameters related to the persistence lifecycle of instances of the mapped class such as:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Primary key mapping and generation scheme</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Object-field-to-table-column mappings</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Associations/Collections</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Caching settings</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Custom SQL, store procedure calls, filters, parameterized queries, and more</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Persistence Lifecycle of Hibernate</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">There are three possible states for a Hibernate mapped object. Understanding these states and the actions that cause state transitions will become very important when dealing with the more complex Hibernate problems.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-JorRt7NwH8k/VEtdO3EMCpI/AAAAAAAAIlw/fwCZx_2JNBg/s1600/Hibernate_persistence_lifecycle_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-JorRt7NwH8k/VEtdO3EMCpI/AAAAAAAAIlw/fwCZx_2JNBg/s1600/Hibernate_persistence_lifecycle_java_latte.png" height="545" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>In the transient state</b>, the object is <span style="color: blue;">not associated</span> with a <span style="color: blue;">database table</span>. That is, its state has not been saved to a table, and the object has <span style="color: blue;">no associated database identity</span> (no primary key has been assigned). Objects in the transient state are non-transactional, meaning that they <span style="color: blue;">do not participate in the scope of any transaction</span> bound to a Hibernate Session. After a successful invocation of the <b>save </b>or <b>saveOrUpdate </b>methods an object ceases to be transient and becomes <span style="color: blue;">persistent</span>. The Session <b>delete </b>method (or a delete query) produces the inverse effect making a persistent object transient.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Persistent objects</b> are objects with database identity. (If they have been assigned a primary key but have not yet been saved to the database, they are referred to as being in the “new” state). Persistent objects are <span style="color: blue;">transactional</span>, which means that they <span style="color: blue;">participate in transactions associated with the Session</span> (at the end of the transaction the object state will be synchronized with the database).</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A persistent object that is no longer in the Session cache (associated with the Session) becomes a <b>detached object</b>. This happens after a transaction completes, when the Session is <span style="color: blue;">closed</span>, <span style="color: blue;">cleared</span>, or if the object is explicitly <span style="color: blue;">evicted from the Session cache</span>. Given Hibernate transparency when it comes to providing persistent services to an object, objects in the detached state can effectively become intertier transfer objects and in certain application architectures can replace the need to have DTOs (Data Transfer Objects).</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">I believe this has cleared you concept of how hibernate works and its components.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;"> with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com9tag:blogger.com,1999:blog-5855689509747625696.post-75143384723127143442014-10-23T12:13:00.000+05:302014-10-23T12:37:00.251+05:30NIO (New Input/Output) vs IO (Input/Output) and NIO.2 in Java <div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;"><b>Non-blocking I/O</b> (usually called <span style="color: blue;"><b>NIO</b></span>, and sometimes called "New I/O") is a collection of Java programming language APIs that offer features for intensive I/O operations. It was introduced with the J2SE 1.4 release of Java to complement an existing standard I/O. An extension to NIO that offers a new file system API, called <b><span style="color: blue;">NIO2</span></b>, was released with Java SE 7. In this article, we understand the concept of NIO and how is it useful as compare to <span style="color: blue;">IO</span> (<span style="color: blue;">java.io.*</span>). </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-2xVm-PDyPik/VEigYsTQB2I/AAAAAAAAIk4/QmbS2eLVdrM/s1600/IO_VS_NIO_Java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-2xVm-PDyPik/VEigYsTQB2I/AAAAAAAAIk4/QmbS2eLVdrM/s1600/IO_VS_NIO_Java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<b style="font-family: 'Trebuchet MS', sans-serif; font-size: x-large;">What Is Input/Output</b><br />
<span style="font-family: Trebuchet MS, sans-serif;">Input/output (I/O) deals with reading data from a <span style="color: blue;">source</span> and writing data to a <span style="color: blue;">destination</span>. Data is read from the input source (or simply input) and written to the output destination (or simply output). <b>For example</b>, your <span style="color: blue;">keyboard</span> works as a standard input, letting you read data entered using the keyboard into your program. You have been using the <span style="color: blue;">System.out.println()</span> method to print text on the standard output from the very first Java program without your knowledge that you have been performing I/O.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The<b> <span style="color: blue;">java.io</span></b> and <span style="color: blue;"><b>java.nio</b></span> (nio stands for New I/O) packages contain Java classes that deal with I/O. The java.io package has an <span style="color: blue;">overwhelming number of classes</span> to perform I/O. It makes learning Java I/O a little complex. The situation where the number of classes increases to an unmanageable extent is called a <b>class explosion</b> and the <span style="color: blue;">java.io package is a good example</span> of that.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Input/Output Streams</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The literal meaning of the word stream is "<span style="color: blue;"><i>an unbroken flow of something</i></span>." In Java I/O, a stream means an unbroken flow (or sequential flow) of data. The data in the stream could be bytes, characters, objects, etc.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A river is a stream of water where the water flows from a source to its destination in an unbroken sequence. Similarly, in Java I/O, the data flows from a source known as a <b>data source</b> to a destination known as a <b>data sink</b>. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The data is read from a <span style="color: blue;">data source to a Java program</span>. A Java program writes <span style="color: blue;">data to a data sink</span>. The <span style="color: blue;">stream</span> that <span style="color: blue;">connects</span> a data source and a Java program is called an <b>input stream</b>. The stream that connects a Java program and a data sink is called an <b>output stream</b>. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In a natural stream, such as a river, the source and the destination are connected through the </span><span style="font-family: 'Trebuchet MS', sans-serif;">continuous flow of water. However, in Java I/O, a Java program comes between an input stream and an output stream. Data flows from a data source through an input stream to a Java program. The data flows from the Java program through an output stream to a data sink. In other words, a Java program reads data from the input stream and writes data to the output stream. Following diagram the flow of data from an input stream to a Java program and from a Java program to an output stream.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-JkPccsuZib0/VEiaIIEFCpI/AAAAAAAAIkM/75wzTRd_iX4/s1600/Old_IO_package.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-JkPccsuZib0/VEiaIIEFCpI/AAAAAAAAIkM/75wzTRd_iX4/s1600/Old_IO_package.png" height="362" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>How we work with input/output stream</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">To read data from a data source into a Java program, you need to perform the following steps:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Identify the data source. It may be a file, a string, an array, a network connection, etc.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Construct an input stream using the data source that you have identified.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Read the data from the input stream. Typically, you read the data in a loop until you have read all the data from the input stream. The methods of an input stream return a special value to indicate the end of the input stream.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Close the input stream. Note that constructing an input stream itself opens it for reading. There is no explicit step to open an input stream. However, you must close the input stream when you are done reading data from it</span></li>
</ul>
<div>
<span style="color: blue; font-family: Trebuchet MS, sans-serif;">To write data to a data sink from a Java program, you need to perform the following steps:</span></div>
<br />
<div style="text-align: left;">
</div>
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Identify the data sink. That is, identify the destination where data will be written. It may be a file, a string, an array, a network connection, etc.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Construct an output stream using the data sink that you have identified.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Write the data to the output stream.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Close the output stream. Note that constructing an output stream itself opens it for writing.There is no explicit step to open an output stream. However, you must close the output stream when you are done writing data to it.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">Input/output stream classes in Java are based on the decorator pattern.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>What Is NIO?</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The stream-based I/O uses streams to transfer data between a data <span style="color: blue;">source/sink</span> and a <span style="color: blue;">Java program</span>. The Java program reads from or writes to a stream a byte at a time. This approach to performing <span style="color: blue;">I/O</span> operations is <span style="color: blue;">slow</span>. The New Input/Ouput (NIO) solves the slow speed problem in the older stream-based I/O.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In NIO, you deal with <b>channels</b> and <b>buffers</b> for I/O operations. A <span style="color: blue;">channel</span> is <span style="color: blue;">like a stream</span>. It represents a connection <span style="color: blue;">between a data source/sink and a Java program</span> for data transfer. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">There is one <span style="color: blue;">difference</span> between a <span style="color: blue;">channel</span> and a <span style="color: blue;">stream</span>. </span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: 'Trebuchet MS', sans-serif;">A stream can be used for <span style="color: blue;">one-way</span> data transfer. That is, an input stream can only transfer data from a data source to a Java program; an output stream can only transfer data from a Java program to a data sink. </span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">However, a channel provides a <span style="color: blue;">two-way</span> data transfer facility. </span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">You can use a channel to read data as well as to write data. You can obtain a read-only channel, a write-only channel, or a read-write channel depending on your needs.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-5yDeLt3aQQ4/VEibsMPge5I/AAAAAAAAIkY/Y5r1Ahdr-J4/s1600/new_IO_package.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-5yDeLt3aQQ4/VEibsMPge5I/AAAAAAAAIkY/Y5r1Ahdr-J4/s1600/new_IO_package.png" height="286" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>In stream-based I/O</b>, the basic unit of data transfer is a <span style="color: blue;">byte</span>. In channel-based NIO, the basic unit of data transfer is a <span style="color: blue;">buffer</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A buffer is a <span style="color: blue;">bounded data container</span>. That is, a buffer has a fixed capacity that determines the upper limit of the data it may contain. In <span style="color: blue;">stream-based I/O</span>, you write data directly to the stream. In <span style="color: blue;">channel-based I/O</span>, you write data into a <span style="color: blue;">buffer</span>; you pass that buffer to the channel, which writes the data to the data sink. Similarly, when you want to read data from a data source, you pass a buffer to a channel. The channel reads data from the data source into a buffer. You read data from the buffer. Above diagram depicts the interaction between a channel, a buffer, a data source, a data sink, and a Java program. It is evident that the<span style="color: blue;"> most important parts</span> in this interaction are <span style="color: blue;">reading from a buffer and writing into a buffer</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>New Input/Output 2 (NIO.2)</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Java 7 introduced New Input/Output 2 (NIO.2) API, which provides a new I/O API. It provides many features that were lacking in the original File I/O API. The features provided in NIO.2 are essential for working with a file system efficiently. It adds three packages to the Java class library:<span style="color: blue;"> java.nio.file</span>,<span style="color: blue;"> java.nio.file.attribute</span>, and <span style="color: blue;">java.nio.file.spi</span>. The following are some of the new features of NIO.2:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">It lets you<span style="color: blue;"> deal with all file systems</span> in a uniform way. The file system support provided by NIO.2 is extensible. You can use the default implementation for a file system or you can choose to implement your own file system.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">It supports basic file operations (<span style="color: blue;">copy, move, and delete</span>) on all file systems. It supports an atomic file move operation. It has improved exception handling support.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">It has support for <span style="color: blue;">symbolic links</span>. Whenever applicable, operations on a symbolic link are redirected to the target file.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">One of the most important additions to NIO.2 is the support for <span style="color: blue;">accessing the attributes</span> of file systems and files.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">It lets you create a <span style="color: blue;">watch service to watch for any events on a directory</span> such as adding a new file or a subdirectory, deleting a file, etc. When such an event occurs on the directory, your program receives a notification through the watch service.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">It added an API that lets you <span style="color: blue;">walk through a file tree</span>. You can perform a file operation on a node as you walk through the file tree.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">It supports <span style="color: blue;">asynchronous I/O on network sockets and files.</span></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">It supports <span style="color: blue;">multicasting</span> using a <span style="color: blue;">DatagramChannel</span>.</span></li>
</ul>
<div>
<br /></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">I hope this article has covered the basic introduction to NIO2 and how it differ from IO.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;"> with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-85757818595481954822014-10-22T12:23:00.001+05:302014-10-22T14:41:23.502+05:30How to Join Threads in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In some situations, we will have to wait for the finalization of a thread. For example, we may have a program that will begin initializing the resources it needs before proceeding with the rest of the execution. We can run the initialization tasks as threads and wait for its finalization </span><span style="font-family: 'Trebuchet MS', sans-serif;">before continuing with the rest of the program. For this purpose, we can use the join() method of the Thread class. When we call this method using a thread object, it suspends the execution of the calling thread until the object called finishes its execution. In this article, we are going to explore Join method of thread class.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-MzdzE928EDo/VEdUQRts3aI/AAAAAAAAIjo/QF7BqpVXDYc/s1600/Thread_join_example_java_latte.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-MzdzE928EDo/VEdUQRts3aI/AAAAAAAAIjo/QF7BqpVXDYc/s1600/Thread_join_example_java_latte.jpg" height="386" width="400" /></a></div>
<br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;"><b>I will Join You in Heaven</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">I can rephrase this section heading as <span style="color: blue;">"I will wait until you die.</span>" That’s right. A thread can wait for another thread to die (or terminate).</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">Suppose</span> there are two threads, t1 and t2. If the thread t1 executes t2.join(), thread t1 starts waiting until thread t2 is terminated. In other words, the call t2.join() blocks until t2 terminates. Using the join() method in a program is <span style="color: blue;">useful</span> if one of the <span style="color: blue;">threads cannot proceed until another thread has finished executing</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>An example</b> where you want to print a message on the standard output when the program has finished executing. The message to print is "Printing Done."</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-a7kWJzoFphI/VEdOuMg9j2I/AAAAAAAAIis/EQx2q785HsI/s1600/Join_method_example1_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-a7kWJzoFphI/VEdOuMg9j2I/AAAAAAAAIis/EQx2q785HsI/s1600/Join_method_example1_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Output</b>:</span><br />
<span style="font-family: 'Trebuchet MS', sans-serif;">Printing Done</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 0</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 1</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 2</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 3</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 4</span><br />
<br />
<br />
<span style="font-family: Trebuchet MS, sans-serif;">In the main() method, a thread is created and started. The thread prints integers from 0 to 4. It sleeps for 3 second after printing an integer. In the end, the main() method prints a message. It seems that this program should print the numbers from 0 to 4, followed by your last message. However, if you look at the output, it is in the reverse order. <span style="color: red;">What is wrong with this program?</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">JVM</span> starts a new thread called <b>main</b> that is<span style="color: blue;"> responsible for executing the main() method</span> of the class that you run. In your case, the main() method of the JoinWrong class is executed by the main thread</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When the<span style="color: blue;"> t1.start() </span>method call <span style="color: blue;">returns</span>, you have one more thread running in your program (thread t1) in addition to the main thread. The t1 thread is responsible for printing the integers from 0 to 4, whereas the main thread is responsible for printing the message <span style="color: blue;"><i>"Printing Done."</i></span> Since there are two threads responsible for two different tasks, <span style="color: blue;">it is not guaranteed</span> which task will finish first. What is the solution? You must make your main thread wait on the thread t1 to terminate. <b>This can be achieved by</b> calling the <span style="color: blue;">t1.join() method inside the main() method</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Following example</b> using the t1.join() method call, before printing the final message. When the main thread executes the join() method call, it waits until the t1 thread is terminated. The join() method of the Thread class throws a java.lang.InterruptedException, and your code should be ready to handle it.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-yOJAWPJKk7M/VEdQAvHl-hI/AAAAAAAAIi4/IbhcT7wrBB0/s1600/Join_method_example2_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-yOJAWPJKk7M/VEdQAvHl-hI/AAAAAAAAIi4/IbhcT7wrBB0/s1600/Join_method_example2_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Output</b>:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 0</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 1</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 2</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 3</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Counter = 4</span><br />
<span style="font-family: 'Trebuchet MS', sans-serif;">Printing Done</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;">Java provides two additional forms of the join() method:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">join</span> (long <span style="color: blue;">milliseconds</span>)</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">join</span> (long <span style="color: blue;">milliseconds</span>, long <span style="color: blue;">nanos</span>)</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">In the first version of the <span style="color: blue;">join</span>() method, instead of <span style="color: blue;">waiting indefinitely</span> for the finalization of the thread called, the calling thread waits for the milliseconds specified as a parameter of the method. .</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">For example, if the object thread1 has the code, thread2.join(1000) , the thread thread1 suspends its execution until one of these two conditions is true:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">thread2 finishes its execution</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">1000 milliseconds have been passed</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">When one of these two conditions is true, the join() method returns. The second version of the join() method is similar to the first one, but receives the number of milliseconds and the number of nanoseconds as parameters.</span></div>
<br />
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: red;"><span style="font-size: large;">Can a thread join multiple threads?</span> </span>The answer is <span style="color: blue;">yes</span>. A thread can join multiple threads like so:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">t1.join(); // Join t1</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">t2.join(); // Join t2</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">t3.join(); // Join t3</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">You should <span style="color: blue;">call the join() method of a thread after it has been <b>started</b></span>. If you call the join() method on a thread that has not been started, it returns immediately. Similarly, if you invoke the join() method on a thread that is already terminated, it returns immediately.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>This example </b>will explain the use where multiple thread call the join method. In this example, we simulate reading of configuration such as network and data source loading before starting out main application.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-VaFHUd0hrbk/VEdSCTK4HgI/AAAAAAAAIjE/XyXEx8-mvJw/s1600/Thread_join_example_dsLoader_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-VaFHUd0hrbk/VEdSCTK4HgI/AAAAAAAAIjE/XyXEx8-mvJw/s1600/Thread_join_example_dsLoader_java.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-qNON_ziqR-o/VEdSC2kXskI/AAAAAAAAIjM/XcRsPX3HhnE/s1600/Thread_join_example_ntLoader_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-qNON_ziqR-o/VEdSC2kXskI/AAAAAAAAIjM/XcRsPX3HhnE/s1600/Thread_join_example_ntLoader_java.png" /></a></div>
<a href="http://1.bp.blogspot.com/-pzalRk0uyH0/VEdSCkuO1cI/AAAAAAAAIjI/h5rUyjyqBho/s1600/Thread_join_example_initialization_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" src="http://1.bp.blogspot.com/-pzalRk0uyH0/VEdSCkuO1cI/AAAAAAAAIjI/h5rUyjyqBho/s1600/Thread_join_example_initialization_java.png" /></a><br />
<b>Output:</b><br />
<span style="font-family: Trebuchet MS, sans-serif;">Beginning data source loading at : Wed Oct 22 12:14:57 IST 2014</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Beginning Network connection loading at : Wed Oct 22 12:14:57 IST 2014</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Beginning data source loading finished at : Wed Oct 22 12:15:01 IST 2014</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Beginning Network connection finished at : Wed Oct 22 12:15:03 IST 2014</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">C</span><span style="font-family: 'Trebuchet MS', sans-serif;">onfiguration has loaded</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>How it works...</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When you run this program, you can see how both Thread objects start their execution. First, the DataSourcesLoader thread finishes its execution. Then, the NetworkConnectionsLoader class finishes its execution and, at that moment, the main Thread object continues its execution and writes the final message.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post</span><span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; line-height: 18.2000007629395px;"> with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com0tag:blogger.com,1999:blog-5855689509747625696.post-23253033742321013952014-10-17T16:16:00.001+05:302014-10-17T16:16:33.589+05:30Builder Design Pattern in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">The builder pattern is a software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. In this article, we look into the implementation of builder pattern in Java with UML diagram as well its real life example.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-4E3YXzluYUI/VEDw04SS6_I/AAAAAAAAIbc/f7f9EoOKUM8/s1600/pizza_builder_patter_example.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-4E3YXzluYUI/VEDw04SS6_I/AAAAAAAAIbc/f7f9EoOKUM8/s1600/pizza_builder_patter_example.jpg" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="color: blue; font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Builder Pattern vs Factory method pattern</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">This is the general question or doubt we usually face when we have to decide when to use factory method pattern and builder pattern. If you need to refresh your concept of factory method pattern, check <a href="http://java-latte.blogspot.in/2014/02/factory-method-design-pattern-in-java.html">my post on Factory pattern</a> . </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>A factory </b>is simply a wrapper function around the constructor. The principle difference is that a factory method pattern require the<span style="color: blue;"> entire object to be built in a single call</span>, will all the parameters pass in on a single line. Then final object will be return.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A real life example can be "meal of the day" in a restaurant. The creation of the meal is a factory pattern, because you tell the kitchen get me the meal of today and the <span style="color: blue;">kitchen decide</span> what object to generate based on the hidden criteria. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>A builder pattern</b>, whereas is a wrapper object around all the possible parameters you might want to pass to a constructor. This allows you to use setter method to build your own parameter list.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A real life example appears if you order a <b>custom pizza</b> ( any drink). In this case, waiter tell the chef ( TeaBuilder, CoffeeBuilder in our example, you will see soon) I need a pizza; add extra cheese, olives, and corn to it. Therefore, the builder exposes the attributes the generated object should have, but hide how to set them.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The Builder is only needed when an object cannot be produced in one step. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Builder Design Pattern UML Diagram</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-zD0hl69-J90/VEDpzhlO8FI/AAAAAAAAIac/4NXfiev3JBM/s1600/Builder_UML_diagram.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-zD0hl69-J90/VEDpzhlO8FI/AAAAAAAAIac/4NXfiev3JBM/s1600/Builder_UML_diagram.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: 'Trebuchet MS', sans-serif;"><b><span style="font-size: large;">Builder Design Pattern Java Code Example</span></b></span><br />
<span style="font-family: 'Trebuchet MS', sans-serif;"><b><br /></b></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-33tUqmaevYM/VEDwXigrAOI/AAAAAAAAIa0/BRe6ArHWrKQ/s1600/Builder_design_pattern_Product_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-33tUqmaevYM/VEDwXigrAOI/AAAAAAAAIa0/BRe6ArHWrKQ/s1600/Builder_design_pattern_Product_class.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-PFsJs6zoqLE/VEDwW0lauZI/AAAAAAAAIaw/tV-wSogTOvI/s1600/Builder_design_pattern_AsbtractBuilder_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-PFsJs6zoqLE/VEDwW0lauZI/AAAAAAAAIaw/tV-wSogTOvI/s1600/Builder_design_pattern_AsbtractBuilder_class.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-JyUT2tH_TMw/VEDwWx-gsWI/AAAAAAAAIbU/oGc1wBEGQZg/s1600/Builder_design_pattern_CoffeeBuilder_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-JyUT2tH_TMw/VEDwWx-gsWI/AAAAAAAAIbU/oGc1wBEGQZg/s1600/Builder_design_pattern_CoffeeBuilder_class.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-yhbLnFLkM6A/VEDwYNpR4jI/AAAAAAAAIa8/-mymrAEdxT8/s1600/Builder_design_pattern_TeaBuilder_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-yhbLnFLkM6A/VEDwYNpR4jI/AAAAAAAAIa8/-mymrAEdxT8/s1600/Builder_design_pattern_TeaBuilder_class.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-q527Bu_bwz8/VEDwYRSt3nI/AAAAAAAAIbA/JXQjUWoXles/s1600/Builder_design_pattern_WaiterDirector_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-q527Bu_bwz8/VEDwYRSt3nI/AAAAAAAAIbA/JXQjUWoXles/s1600/Builder_design_pattern_WaiterDirector_class.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-OixeqzCdZXg/VEDwW24sMtI/AAAAAAAAIas/JYN7uHKs6QY/s1600/Builder_design_pattern_Customer_class.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-OixeqzCdZXg/VEDwW24sMtI/AAAAAAAAIas/JYN7uHKs6QY/s1600/Builder_design_pattern_Customer_class.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Structure of above example</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-0Gt9KamuueQ/VEDxsq9Hp7I/AAAAAAAAIb0/XV5ZkmDRT64/s1600/Builder_design_flow.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-0Gt9KamuueQ/VEDxsq9Hp7I/AAAAAAAAIb0/XV5ZkmDRT64/s1600/Builder_design_flow.png" height="200" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Example in Java</b> </span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html#append%28boolean%29">java.lang.StringBuilder#append()</a></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html#append%28boolean%29">java.lang.StringBuffer#append()</a></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><a href="http://docs.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html#put%28byte%29">java.nio.ByteBuffer#put()</a> (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)</span></li>
</ul>
<br />
<br />
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span><br />
<br /></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com0tag:blogger.com,1999:blog-5855689509747625696.post-34527789417150910692014-10-08T22:24:00.001+05:302014-10-08T22:24:35.175+05:30Lifecycle of Java Server Pages<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we look into the life-cycle of Java Server pages (JSP) along with its phases descriptions. Also, we see the flow of JSP handling the request and in what phases it goes and what would happened at the end after serving request.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/--CojSELmkws/VDVrS4TJfYI/AAAAAAAAIWE/SlVMz2ULaZM/s1600/JSP_lifecycle.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/--CojSELmkws/VDVrS4TJfYI/AAAAAAAAIWE/SlVMz2ULaZM/s1600/JSP_lifecycle.jpg" height="372" width="400" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Java Server Pages</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Java Server Pages (JSPs) are a simple but powerful technology used most often to generate dynamic HTML on the server side. They are a <span style="color: blue;">direct extension</span> of Java servlets with the purpose of allowing the developer to embed Java logic directly into a requested document. Using JSP Expression Language, you can develop powerful dynamic web pages powered by Java servlets without any Java code. A JSP document must end with a <span style="color: blue;">.jsp</span> extension.</span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif;">JSP page is processed in several phases during its lifecycle. Following table will describes all the phases of the JSP lifecycle.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-lK9QHhjsohA/VDVaklvZrbI/AAAAAAAAIVs/-j4cnDC_npY/s1600/lifecycle_of_JSP_and_its_phase_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-lK9QHhjsohA/VDVaklvZrbI/AAAAAAAAIVs/-j4cnDC_npY/s1600/lifecycle_of_JSP_and_its_phase_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><span id="goog_316881941"></span><span id="goog_316881942"></span>The <span style="color: blue;">first time</span> the file is requested, it is <span style="color: blue;">translated into a <b>servlet</b></span><b> </b>and then compiled into a <span style="color: blue;">servlet class</span> that is loaded into resident memory. The JSP page then becomes a standard Java servlet, and it goes through the same lifecycle steps as servlet go: the servlet is <span style="color: blue;">instantiated</span>, <span style="color: blue;">initialized</span>, and it finally <span style="color: blue;">starts to service</span> the client requests until it’s destroyed. After the loaded JSP servlet services each request, the output is sent back to the requesting client.</span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The servlet generated from the JSP file implements j<span style="color: blue;">avax.servlet.jsp.<b>HttpJspPage</b></span><b> </b>interface, which is responsible for its lifecycle. This interface is very similar to the servlet lifecycle, but with JSP-specific features. The lifecycle methods of the HttpJspPage interface correspond with the Servlet interface methods: </span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: 'Trebuchet MS', sans-serif;"><span style="color: blue;">HttpJspPage</span>.<b>jspInit</b>(..) for jsp servlet initialization</span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;"><span style="color: blue;">HttpJspPage</span>.<b>jspService</b>(..) for request servicing </span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;"><span style="color: blue;">HttpJspPage</span>.<b>jspDestroy</b>(..) for jsp servlet destruction.</span></li>
</ul>
<br />
<b style="font-family: 'Trebuchet MS', sans-serif; font-size: x-large;">Steps of JSP request</b><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;">On all subsequent requests, the server checks to see whether the original .jsp source file has changed. If it has not changed, the server invokes the <span style="color: blue;">previously compiled</span> servlet object, <span style="color: blue;">skipping </span>the <span style="color: blue;">translation </span>and <span style="color: blue;">compilation </span>phases. If the source has changed, however, the JSP engine re-parses the JSP source, going to all phases of the JSP lifecycle.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-JSOgf-A0CVY/VDValQsxcUI/AAAAAAAAIVw/4envH3e4gdY/s1600/Life_cycle_of_jsp_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-JSOgf-A0CVY/VDValQsxcUI/AAAAAAAAIVw/4envH3e4gdY/s1600/Life_cycle_of_jsp_in_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: red;"><br /></span></b></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: red;">Note </span></b>An essential point to remember about <span style="color: blue;">JSPs is that they are just servlets</span> that are created from a combination of HTML and Java source. Therefore, they have the same resources and functionality of a servlet.</span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span><span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
</div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com2tag:blogger.com,1999:blog-5855689509747625696.post-60989106554365479272014-10-07T16:45:00.000+05:302014-10-07T16:45:37.603+05:30How to traverse Collection in Java using Iterator, for-each loop and forEach method<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we look into difference method for iterating over the Collection such as Iterator, for-each loop and forEach method of Java 8 with examples. We also see the difference between them.</span><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;">
<a href="http://3.bp.blogspot.com/-mYnUxWjfKf4/VDPK8ylEypI/AAAAAAAAISU/HHdoEGvXt2Y/s1600/traverse_collection_in_java_latte.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-mYnUxWjfKf4/VDPK8ylEypI/AAAAAAAAISU/HHdoEGvXt2Y/s1600/traverse_collection_in_java_latte.jpg" height="310" width="640" /></a></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">Most often, you need to access all elements of a collection one at a time. Different types of collections store their elements differently using different types of data structures. Some collections impose ordering on their elements and some do not. The Collections Framework provides the following ways to traverse a collection:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Using an <b>Iterator</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Using a <b>for-each</b> loop</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Using the <b>forEach()</b> method</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">Some collections, such as lists, assign each element <span style="color: blue;">an index</span> and they let you access their elements using <span style="color: blue;">indexes</span>. You can traverse those collections using a <span style="color: blue;">regular for-loop</span> statement as well. You can also traverse collections by converting them into streams and performing an aggregate operation on those streams.</span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Iterator</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A collection provides an iterator to iterate over all its elements. Sometimes an iterator is also known as a <span style="color: blue;">generator</span> or a <span style="color: blue;">cursor</span>. An iterator lets you perform the following three operations on a collection:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Check if there are elements that have not been yet accessed using this iterator.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Access the next element in the collection.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Remove the last accessed element of the collection.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">The<span style="color: blue;"> iterator itself does not impose any ordering </span>in which it returns the elements from a collection. However, if the collection imposes ordering on its elements, the iterator will maintain the same ordering.</span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">An <b>iterator</b> in Java is an instance of the <span style="color: blue;">Iterator<E></span> interface. You can get an iterator for a collection using the iterator() method the Collection interface.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The Iterator<E> interface contains the following methods:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">boolean <b>hasNext()</b> : The hasNext() method returns true if there are more elements in the collection to iterate. Otherwise, it returns false.Typically, you call this method before asking the iterator for the next element from the collection.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">E <b>next()</b> : returns the next element from the collection. You <span style="color: blue;">should always</span> call the hasNext() method <span style="color: blue;">before</span> calling the next() method. If you call the next() method and the iterator has no more elements to return, it throws a <span style="color: red;">NoSuchElementException</span>.<br /></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">default void <b>remove()</b> : removes the element of the collection that was returned last time by calling the next() method of the iterator. The <span style="color: blue;">remove()</span> method can be <span style="color: blue;">called only once per call</span> to the next() method. If the remove() method is called more than once per next() method call or before the first call to the next() method, it throws an <span style="color: red;">IllegalStateException</span><br /></span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">default void </span><b style="font-family: 'Trebuchet MS', sans-serif;">forEachRemaining(Consumer<? super E> action)</b><span style="font-family: 'Trebuchet MS', sans-serif;"> : is new to Java 8 and takes an action on each element of the collection that has not been accessed by the iterator yet. The action is specified as a Consumer. For more information on this, please check my previous post on <a href="http://java-latte.blogspot.in/2014/03/stream-lambda-in-java-8.html">Lambda</a> and <a href="http://java-latte.blogspot.in/2014/03/method-references-in-java-8.html">Method reference</a>.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">The Collections Framework supports <span style="color: blue;">fast-fail concurrent</span> iterators. You can obtain multiple iterators for a collection and all of them can be used to iterate over the same collection concurrently. If the collection is modified by any means, except using the remove() method of the same iterator after the iterator is obtained, the attempt to access the next element using the iterator will throw a <span style="color: blue;">ConcurrentModificationException</span>. It means that you can have multiple iterators for a collection; however, all iterators must be accessing (reading) elements of the collection. If any of the iterators modify the collection using its remove() method, the iterator that modifies the collection will be fine and all other iterators will fail. If the collection is modified outside of all iterators, all iterators will fail.</span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-qfvST-sgAwU/VDPFrye531I/AAAAAAAAIRo/vhxMaKHokUE/s1600/Iterator_to_Iterate_over_collection2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-qfvST-sgAwU/VDPFrye531I/AAAAAAAAIRo/vhxMaKHokUE/s1600/Iterator_to_Iterate_over_collection2.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">The code uses method reference System.out::println as a <span style="color: blue;">Consumer</span> for the forEachRemaining() method. Notice that using the forEachRemaining() method helps shorten the code by eliminating the need for a loop using the hasNext() and next() methods. Please refer method <a href="http://java-latte.blogspot.in/2014/03/method-references-in-java-8.html">reference article</a> .</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/--6FRfNntNGM/VDPFr85lHyI/AAAAAAAAIRk/2mU0H2k0g6U/s1600/Iterator_to_Iterate_over_collection.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/--6FRfNntNGM/VDPFr85lHyI/AAAAAAAAIRk/2mU0H2k0g6U/s1600/Iterator_to_Iterate_over_collection.png" /></a></div>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span></div>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span></div>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><u>Things to remember for Iterator</u></span></div>
<br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: 'Trebuchet MS', sans-serif;">An </span><span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">Iterator</span><span style="font-family: 'Trebuchet MS', sans-serif;"> is a </span><b style="font-family: 'Trebuchet MS', sans-serif;">one-time</b><span style="font-family: 'Trebuchet MS', sans-serif;"> object.</span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">You </span><b style="font-family: 'Trebuchet MS', sans-serif;">cannot</b><span style="font-family: 'Trebuchet MS', sans-serif;"> </span><b style="font-family: 'Trebuchet MS', sans-serif;">reset</b><span style="font-family: 'Trebuchet MS', sans-serif;"> an iterator. </span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">It <b>cannot be reused</b> to iterate over the element of the collection. </span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">If you need to iterate over the elements of the same collection again, you need to obtain a new Iterator calling the iterator() method of the collection.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>for-each Loop</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">You can use the for-each loop to iterate over elements of a collection that hides the logic to set up an iterator for a collection.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">You can use the <span style="color: blue;">for-each</span> loop to iterate <span style="color: blue;">over any collection</span> whose implementation class implements the <span style="color: blue;">Iterable</span> <span style="color: blue;">interface</span>. The Collection interface inherits from the Iterable interface, and therefore, you can use the for-each loop with all types of collections that implement the Collection interface. For example, the <span style="color: blue;">Map</span> collection type <span style="color: blue;">does not inherit</span> from the <span style="color: blue;">Collection interface</span>, and therefore, you cannot use the for-each loop to iterate over entries in a Map.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The for-each loop is <span style="color: blue;">simple</span> and <span style="color: blue;">compact</span>. Behind the scenes, it gets the iterator for your collection and calls the hasNext() and next() methods for you. You can iterate over all elements of a list of string as follows:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-ij1OUW_9-k8/VDPDDDpkviI/AAAAAAAAIRM/PCJVFzMuziY/s1600/For-each-method_to_iterate_collection.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-ij1OUW_9-k8/VDPDDDpkviI/AAAAAAAAIRM/PCJVFzMuziY/s1600/For-each-method_to_iterate_collection.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">The for-each loop is<span style="color: blue;"> not a replacement</span> for using an <span style="color: blue;">iterator</span>. The for-each loop has <span style="color: red;">several limitations</span>, though. You cannot use the for-each loop everywhere you can use an iterator. For example, you <span style="color: blue;">cannot use the for-each loop to remove elements </span>from the collection.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><b>Another limitation</b> of the for-each loop is that you <span style="color: blue;">must traverse from the first</span> element to the last element of the collection. It provides <span style="color: blue;">no way to start from middle of the collection</span>. The for-each loop provides no way to visit the previously visited elements, which is allowed by the iterator of some collection types such as lists.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>forEach() Method</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The<span style="color: blue;"> Iterable interface</span> contains a new <span style="color: blue;">forEach(Consumer<? super T> action)</span> method that you can use in all collection types that inherit from the Collection interface. The method iterates over all elements and applies the action.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">It works similar to the <span style="color: blue;">forEachRemaining(Consumer<? super E> action)</span> method of the Iterator interface with a difference that the <span style="color: blue;">Iterable.forEach()</span> method iterates<span style="color: blue;"> over all elements</span> whereas the <span style="color: blue;">Iterator.forEachRemaining()</span> method iterates over the elements in the collections that have <span style="color: blue;">not yet been retrieved</span> by the Iterator.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Tip</b> The Iterator is the fundamental way of iterating over elements of a collection. It has existed since the beginning. All other ways, such as the <b>for-each</b> loop, the <b>forEach</b>() method, and the <b>forEachRemaining</b>() method, are syntactic sugar for the Iterator. <b>Internally</b>, they all use an Iterator .</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-ACAi7tekrS8/VDPErsohvuI/AAAAAAAAIRY/RLIFKkgEsOQ/s1600/For-each_method_to_iterate_collection.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-ACAi7tekrS8/VDPErsohvuI/AAAAAAAAIRY/RLIFKkgEsOQ/s1600/For-each_method_to_iterate_collection.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-19568243489674822712014-10-03T23:39:00.001+05:302014-10-03T23:39:19.878+05:30Why to use @Override Annotation in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">If you are new to annotation in Java, then this article will give an exciting example to understand what Annotation actually means in Java. We'll also understand what is Annotation and why we need them with one example of @Override Annotation.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-gDGp9YtSTcE/VC7iUwRe0bI/AAAAAAAAIQ0/sWEECbghzsI/s1600/Annotation_in_Java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-gDGp9YtSTcE/VC7iUwRe0bI/AAAAAAAAIQ0/sWEECbghzsI/s1600/Annotation_in_Java.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Annotations were introduced in Java 5. Before I define annotations and discuss their importance in programming, let’s discuss a simple example. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Suppose you have an <b>Employee </b>class, which has a method called <span style="color: blue;">setSalary()</span> that sets the salary of an employee. The method accepts a parameter of the type double. The following snippet of code shows a trivial implementation for the Employee class:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-XG60XcPFQKk/VC7glvU4bUI/AAAAAAAAIQQ/J4cGG1NXPaA/s1600/Employee_class_for_annotations.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-XG60XcPFQKk/VC7glvU4bUI/AAAAAAAAIQQ/J4cGG1NXPaA/s1600/Employee_class_for_annotations.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A <b>Manager </b>class inherits from the Employee class. You want to set the salary for managers differently. You decide to override the setSalary() method in the Manager class. The code for the Manager class is as follows</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-LPlihlitO6Q/VC7glkC8IoI/AAAAAAAAIQU/K2lePgm0AgM/s1600/Manger_class_for_annotations.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-LPlihlitO6Q/VC7glkC8IoI/AAAAAAAAIQU/K2lePgm0AgM/s1600/Manger_class_for_annotations.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Note that <span style="color: red;">there is a mistake in the above code</span> for the <span style="color: blue;">Manager </span>class, when you attempt to<span style="color: blue;"> override the setSalary()</span> method. (You’ll correct the mistake shortly.) You have used the <span style="color: blue;">int </span>data type as the parameter type for the <span style="color: blue;">incorrectly overridden method</span>. It is time to set the salary for a manager. The following code is used to accomplish this:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-9jOVGcP7qWs/VC7glkUiRjI/AAAAAAAAIQY/9ZbmVcoHXCY/s1600/Annotation_demo_by_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-9jOVGcP7qWs/VC7glkUiRjI/AAAAAAAAIQY/9ZbmVcoHXCY/s1600/Annotation_demo_by_java_latte.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Output</b> : </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Employee.setSalary():500.0</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">This snippet of code was expected to <span style="color: blue;">call the setSalary() method of the Manager</span> class but the output does <span style="color: blue;">not show the expected result</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: red;"><b>What went wrong in your code?</b></span> The intention of defining the setSalary() method in the Manager class <span style="color: blue;">was to override</span> the setSalary() method of the Employee class, not to overload it. You <span style="color: blue;">made a mistake</span>. You used the type <span style="color: blue;">int </span>as the parameter type in the setSalary() method, instead of the type <span style="color: blue;">double</span>, in the Manager class</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">You put comments indicating your intention to override the method in the Manager class. However, <span style="color: blue;">comments do not stop you from making </span><span style="color: red;">logical </span><span style="color: blue;">mistakes</span>. You might spend, as every programmer does, hours and hours debugging errors resulting from this kind of logical mistake.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b><span style="color: blue;">Who can help you in such situations?</span></b> Annotations might help you in a few situations like this.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Let’s <span style="color: blue;">rewrite your Manager class</span> using an <span style="color: blue;">annotation</span>. You do not need to know anything about annotations at this point. All you are going to do is add one word to your program. The following code is the modified version of the Manager class:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-un82dxpzfiA/VC7h_vaJsaI/AAAAAAAAIQs/RRLicxlqX9E/s1600/Manger_class_with_override_for_annotations.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-un82dxpzfiA/VC7h_vaJsaI/AAAAAAAAIQs/RRLicxlqX9E/s1600/Manger_class_with_override_for_annotations.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">All you have added is a @Override annotation to the Manager class and removed the “<span style="color: blue;">dumb</span>” comments. <span style="color: blue;">Trying to compile</span> the revised Manager class results in a compile-time error that points to the use of the @Override annotation for the setSalary() method of the Manager class:</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">Manager.java:2</span>: <span style="color: red;">error: method does not override or implement a method from a supertype @Override</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The use of the <span style="color: blue;">@Override </span>annotation <span style="color: blue;">did the trick</span>. </span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: 'Trebuchet MS', sans-serif;">The @Override annotation is used with a non-static method to indicate the programmer’s intention to override the method in the superclass. </span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">At source code level, it serves the purpose of documentation. When the compiler comes across the @Override annotation, it makes sure that the method really overrides the method in the superclass. If the method <span style="color: blue;">annotated does not override</span> a method in the superclass, the compiler <span style="color: blue;">generates an error</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">In your case, the setSalary(int salary) method in the <span style="color: blue;">Manager class does not override any method</span> in the superclass Employee. This is the reason that you got the error. You may realize that using <span style="color: blue;">an annotation is as simple as documenting the source code</span>. However, <b>they have compiler support</b>. You can use them to <b>instruct the compiler to enforce some rules</b>. Annotations provide benefits much more than you have seen in this example.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><u>You can fix the error by doing one of the following two things:</u></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">You can <span style="color: blue;">remove the @Override annotation</span> from the setSalary(int salary) method in the Manager class. It will make the method an overloaded method, not a method that overrides its superclass method.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">You can <span style="color: blue;">change the method signature</span> from setSalary(int salary) to setSalary(double salary). Since you want to override the setSalary() method in the Manager class</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><b>Note that the @Override annotation in the setSalary() method of the Manager class saves you <span style="color: blue;">debugging </span>time.</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>What is Annotation</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">It lets you <span style="color: blue;">associate (or annotate) metadata </span>(or notes)<span style="color: blue;"> to the program elements</span> in a Java program. The program elements may be a package, a class, an interface, a field of a class, a local variable, a method, a parameter of a method, an enum, an annotation, a type parameter in a generic type/method declaration, a type use, etc. In other words, you can annotate any declaration or type use in a Java program. An annotation is used as a modifier in a declaration of a program element like any other modifiers (public, private, final, static, etc.). Unlike a modifier, an annotation does not modify the meaning of the program elements. It acts like a decoration or a note for the program element that it annotates.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">An <b>annotation differs from regular documentation</b> in many ways</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">A regular documentation is only for humans to read and it is “dumb.” </span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">An annotation serves this purpose. It is human readable, which serves as documentation. It is compiler readable, which lets the compiler verify the intention of the programmer; for example, the compiler makes sure that the programmer has really overridden the method if it comes across a @Override annotation for a method. Annotations are also available at runtime so that a program can read and use it for any purpose it wants.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>For example</b>, a tool can read annotations and <span style="color: blue;">generate boilerplate code</span>. If you have worked with Enterprise JavaBeans (EJB), you know the pain of keeping all the interfaces and classes in sync and adding entries to XML configuration files. EJB 3.0 uses annotations to generate the boilerplate code, which makes EJB development painless for programmers.</span></div>
<div>
<b style="font-family: 'Trebuchet MS', sans-serif;">Another example</b><span style="font-family: 'Trebuchet MS', sans-serif;"> of an annotation being used in a framework/tool is JUnit version 4.0. JUnit is a unit test framework for Java programs. It uses annotations to mark methods that are test cases. Before that, you had to follow a naming convention for the test case methods. Annotations have a variety of uses, which are documentation, verification, and enforcement by the compiler, the runtime validation, code generation by frameworks/tools, etc.</span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">An annotation <span style="color: blue;">does not change the semantics</span> (or meaning) of the program element that it annotates. In that sense, an <span style="color: blue;">annotation is like a comment</span>, which does not affect the way the annotated program element works. For example, the @Override annotation for the setSalary() method did not change the way the method works.</span><br />
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com1tag:blogger.com,1999:blog-5855689509747625696.post-8913077714887804862014-10-03T14:09:00.000+05:302014-10-03T14:14:36.299+05:30Architecture of Apache Tomcat<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Trebuchet MS, sans-serif;">In this article, we look into the different component of Apache Tomcat architecture that will help us to understand Tomcat in more detail. </span><span style="font-family: 'Trebuchet MS', sans-serif;">The Apache Tomcat server is an open source, Java-based web application container that was created to run </span><span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">servlet</span><span style="font-family: 'Trebuchet MS', sans-serif;"> and </span><span style="color: blue; font-family: 'Trebuchet MS', sans-serif;">JavaServer Pages</span><span style="font-family: 'Trebuchet MS', sans-serif;"> (JSP) web applications.</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-drrYcyBsjHY/VC2epv-hxvI/AAAAAAAAIPI/Dycfhy3m-Ws/s1600/tomcat.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-drrYcyBsjHY/VC2epv-hxvI/AAAAAAAAIPI/Dycfhy3m-Ws/s1600/tomcat.png" height="213" width="320" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Apache Tomcat is very stable and has all of the features of a commercial web application container – yet comes under Open Source Apache License. Tomcat also provides additional functionality that makes it a great choice for developing a complete web application solution. Some of the additional features provided by Tomcat—other than being open source and free—include the <span style="color: blue;">Tomcat Manager application</span>,<span style="color: cyan;"> s</span><span style="color: blue;">pecialized realm implementations</span>, and <span style="color: blue;">Tomcat valves</span>.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Regarding the latest release of Tomcat always check <a href="http://tomcat.apache.org/">Apache Tomcat</a> site.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Architecture of Tomcat</b> </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Before reading this you should look into tomcat conf/server.xml in order to understand this. Download <a href="https://docs.google.com/uc?export=download&id=0B0il3S8nNSm3NDVJZmhhTlkyX2c">server.xml</a> file.<br />A Tomcat instance, or server, is the <span style="color: blue;">top-level component</span> in Tomcat’s container hierarchy. Only one Tomcat instance can live in a single Java Virtual Machine (JVM). This approach makes all other Java applications, running on the same physical machine as Tomcat server, safe in case Tomcat and/or its JVM crashes.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Tomcat instance consists of grouping of the application containers, which exist in the well-defined hierarchy. The key component in that hierarchy is the <span style="color: blue;">Catalina</span> servlet engine. <span style="color: blue;"><b>Catalina</b></span> is the actual Java servlet container implementation as specified in Java Servlet API</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">XML representation of the relationships between the different Tomcat containers. </span><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="http://4.bp.blogspot.com/-_WpqSi6cKOM/VC2X9j9WQ7I/AAAAAAAAIOw/FjYX-HP2PTg/s1600/Tomcat_Architecture_XML_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-_WpqSi6cKOM/VC2X9j9WQ7I/AAAAAAAAIOw/FjYX-HP2PTg/s1600/Tomcat_Architecture_XML_in_java_latte.png" height="226" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-uf_gI_tX5fs/VC2X98gZW1I/AAAAAAAAIO0/FiGP2UmkE6A/s1600/Tomcat_Architecture_main_in_java_latte.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-uf_gI_tX5fs/VC2X98gZW1I/AAAAAAAAIO0/FiGP2UmkE6A/s1600/Tomcat_Architecture_main_in_java_latte.png" height="632" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">This instance can be broken down into a set of containers including a <span style="color: blue;">server</span>, a <span style="color: blue;">service</span>, a <span style="color: blue;">connector</span>, an <span style="color: blue;">engine</span>, a <span style="color: blue;">host</span>, and a <span style="color: blue;">context</span>. By default, each of these containers is configured using the <span style="color: blue;">server.xml</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Server </b></span><br />
<div>
<span style="font-family: Trebuchet MS, sans-serif;">In the Tomcat world, a Server represents the whole container. Tomcat provides a default implementation of the <a href="http://tomcat.apache.org/tomcat-8.0-doc/api/org/apache/catalina/Server.html">Server interface</a> which is rarely customized by users.</span></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">Server is Tomcat itself</span> — an instance of the Web application server — and is a top-level component. It owns a port that is used to shut down the server. In addition, the Server can be set in debug mode, which instantiates a version of the Java Virtual Machine (JVM) that enables debugging.</span><br />
<span style="color: red; font-family: Trebuchet MS, sans-serif;"><i>Only one instance of the Server can be created inside a given Java Virtual Machine (JVM).</i></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Separate Servers configured to different ports can be set up on a single machine to separate applications so that they can be restarted independently. That is, if one Server running in a JVM were to crash, the other applications would be safe in another Server instance. This is sometimes done in hosting environments in which each customer has a separate instance of a JVM, so a badly configured/written application will not cause others to crash.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A Server element represents the entire Catalina servlet container. Therefore, it must be the single outermost element in the <span style="color: red;">conf/server.xml</span> configuration file. Its attributes represent the characteristics of the servlet container as a whole.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">All implementations of Server support the following attributes:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>className</b> : Java class name of the implementation to use. This class must implement the org.apache.catalina.Server interface. If no class name is specified, the standard implementation will be used.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>address</b>: The TCP/IP address on which this server waits for a shutdown command. If no address is specified, localhost is used.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>port </b>: The TCP/IP port number on which this server waits for a shutdown command. Set to -1 to disable the shutdown port.<br />Note: Disabling the shutdown port works well when Tomcat is started using Apache Commons Daemon (running as a service on Windows or with jsvc on un*xes). It cannot be used when running Tomcat with the standard shell scripts though, as it will prevent shutdown.bat|.sh and catalina.bat|.sh from stopping it gracefully.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>shutdown </b>: The command string that must be received via a TCP/IP connection to the specified port number, in order to shut down Tomcat.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>debug </b>: The debug attribute is available to all Tomcat elements. It states the debug level to use when logging messages to a defined Logger.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">Standard Implementation The standard implementation of Server is <span style="color: blue;">org.apache.catalina.core.StandardServer.</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The following components may be nested inside a Server element:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Service - One or more service element.</span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">GlobalNamingResources - Configure the JNDI global resources for the server.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Service</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A Service is an intermediate component which <span style="color: blue;">lives inside a Server</span> and t<span style="color: blue;">ies one or more Connectors to exactly one Engine</span>. The Service element is rarely customized by users, as the default implementation is simple and sufficient</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">"A Service element represents the <span style="color: blue;">combination of one or more Connector</span> components that s<span style="color: blue;">hare a single Engine</span> component for processing incoming requests. One or more Service elements may be nested inside a Server element.</span><span style="font-family: 'Trebuchet MS', sans-serif;">"</span><br />
<span style="font-family: 'Trebuchet MS', sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><i><span style="color: red;">An </span>Engine <span style="color: red;">is a request-processing component that represents the Catalina Servlet engine. It examines the HTTP headers to determine the virtual host or context to which requests should be passed.</span></i></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Each Service represents a grouping of Connectors (components that manage the connection between the client and server) and a single container,<span style="color: blue;"> which accepts requests from the Connectors and processes the requests to present them to the appropriate Host</span>. Each Service is named so that administrators can easily identify log messages sent from each Service.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">In other words, the container contains the Web Applications. It is responsible for accepting requests, routing them to the specified Web application and specific resource, and returning the result of the processing of the request. Connectors stand between the client making the request and the container. They provode additional services such as <span style="color: blue;">SSL </span>request</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">All implementations of Service support the following attributes</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>className</b> : Java class name of the implementation to use. This class must implement the <span style="color: blue;">org.apache.catalina.Service</span> interface. If no class name is specified, the standard implementation will be used</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>name </b>: The display name of this Service, which will be included in log messages if you utilize standard Catalina components. The name of each Service that is associated with a particular Server must be unique.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">The standard implementation of Service is <span style="color: blue;">org.apache.catalina.core.StandardService</span></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Engine</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">An Engine represents request processing pipeline for a specific Service. As a Service may have multiple Connectors, the Engine receives and processes all requests from these connectors, handing the response back to the appropriate connector for transmission to the client.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Exactly one Engine element <span style="color: blue;">MUST </span>be nested inside a Service element, following all of the corresponding Connector elements associated with this Service.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A container object that cannot be contained by another container. This means that it is guaranteed not to have a parent container. It is at this level that the objects begin to aggregate child components. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Strictly speaking, the container does not need to be an Engine, it just has to implement the container interface. This interface mandates the following: that the object implementing it is aware of its position in the hierarchy (it knows its parent and its children), that it provides <span style="color: blue;">access to logging</span>, that it provides a <span style="color: blue;">Realm </span>for user authentication and <span style="color: blue;">role-based authorization</span>, and that it has access to a number of resources, including its <span style="color: blue;">session manager</span> .</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">All implementations of Engine support the following attributes:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>backgroundProcessorDelay </b>: This value represents the delay in seconds between the invocation of the backgroundProcess method on this engine and its child containers, including all hosts and contexts. Child containers will not be invoked if their delay value is not negative (which would mean they are using their own processing thread). Setting this to a positive value will cause a thread to be spawn. After waiting the specified amount of time, the thread will invoke the backgroundProcess method on this engine and all its child containers. If not specified, the default value for this attribute is 10, which represent a 10 seconds delay.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>className </b>: Java class name of the implementation to use. This class must implement the org.apache.catalina.Engine interface. If not specified, the standard value (defined below) will be used.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">defaultHost : The default host name, which identifies the Host that will process requests directed to host names on this server, but which are not configured in this configuration file. This name MUST match the name attributes of one of the Host elements nested immediately inside.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>jvmRoute </b>: Identifier which must be used in load balancing scenarios to enable session affinity. The identifier, which must be unique across all Tomcat servers which participate in the cluster, will be appended to the generated session identifier, therefore allowing the front end proxy to always forward a particular session to the same Tomcat instance.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>name </b>: Logical name of this Engine, used in log and error messages. When using multiple Service elements in the same Server, each Engine MUST be assigned a unique name.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>startStopThreads </b>: The number of threads this Engine will use to start child Host elements in parallel. The special value of 0 will result in the value of Runtime.getRuntime().availableProcessors() being used. Negative values will result in Runtime.getRuntime().availableProcessors() + value being used unless this is less than 1 in which case 1 thread will be used. If not specified, the default value of 1 will be used.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><u>Special Features</u></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">Logging</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Access Logs</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Lifecycle Listeners</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Lifecycle Listeners</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Host</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-DVUwCvH5Gx0/VC5exrfTHrI/AAAAAAAAIP0/TPZhRcSgm6U/s1600/host_tomcat.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-DVUwCvH5Gx0/VC5exrfTHrI/AAAAAAAAIP0/TPZhRcSgm6U/s1600/host_tomcat.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;">The Host element <span style="color: blue;">represents a virtual host</span>, which is an association of a network name for a server (such as "www.mycompany.com" with the particular server on which Tomcat is running. For clients to be able to connect to a Tomcat server using its network name, this name must be registered in the Domain Name Service (DNS) server that manages the Internet domain you belong to.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">One or more Host elements are nested inside an Engine element. Inside the Host element, you can nest Context elements for the web applications associated with this virtual host. <span style="color: blue;">Exactly one of the Hosts associated with each Engine</span> MUST have a name matching the defaultHost attribute of that Engine.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Clients normally <span style="color: blue;">use host names to identify</span> the server they wish to connect to. This host name is also included in the HTTP request headers. Tomcat extracts the host name from the HTTP headers and looks for a Host with a matching name. If no match is found, the request is routed to the default host. The name of the default host does not have to match a DNS name (although it can) since any request where the DNS name does not match the name of a Host element will be routed to the default host.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">All implementations of Host support the following attributes:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>appBase </b>: The Application Base directory for this virtual host. This is the pathname of a directory that may contain web applications to be deployed on this virtual host. You may specify an absolute pathname, or a pathname that is relative to the <span style="color: blue;">$CATALINA_BASE </span>directory.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>xmlBase </b>: The XML Base directory for this virtual host. This is the pathname of a directory that may contain context XML descriptors to be deployed on this virtual host. You may specify an absolute pathname for this directory, or a pathname that is relative to the $CATALINA_BASE directory. </span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>createDirs </b>: If set to true, Tomcat will attempt to create the directories defined by the attributes appBase and xmlBase during the startup phase. The default value is true. If set to true, and directory creation fails, an error message will be printed out but will not halt the startup sequence.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>autoDeploy</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>backgroundProcessorDelay</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>className</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>deployIgnore</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>deployOnStartup </b>: This flag value indicates if web applications from this host should be automatically deployed when Tomcat starts. The flag's value defaults to true</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>failCtxIfServletStartFails</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>name</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>startStopThreads</b></span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;"><b>undeployOldVersions </b>: This flag determines if Tomcat, as part of the auto deployment process, will check for old, unused versions of web applications deployed using parallel deployment and, if any are found, remove them. This flag only applies if autoDeploy is true. If not specified the default value of false will be used.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;">The standard implementation of Host is <span style="color: blue;">org.apache.catalina.core.StandardHost</span>. </span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><u>Special Features</u>:</span><br />
<ul style="text-align: left;">
<li><span style="font-family: 'Trebuchet MS', sans-serif;">Logging</span></li>
<li><span style="font-family: 'Trebuchet MS', sans-serif;">Access Logs</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Automatic Application Deployment</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Host Name Aliases</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Lifecycle Listeners</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Request Filters</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Single Sign On</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">User Web Applications</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Connector</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-YjZG3-lBl3w/VC5eZloWS_I/AAAAAAAAIPs/IcW9_6zFyDk/s1600/Connector_tomcat.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-YjZG3-lBl3w/VC5eZloWS_I/AAAAAAAAIPs/IcW9_6zFyDk/s1600/Connector_tomcat.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A Connector <span style="color: blue;">handles communications with the client</span>. There are multiple connectors available with Tomcat. These include the HTTP connector which is used for most HTTP traffic, especially when running Tomcat as a standalone server, and the AJP connector which implements the AJP procotol used when connecting Tomcat to a web server such as Apache HTTPD server. Creating a customized connector is a significant effort.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><i>Connectors connect the applications to clients. They represent the point at which requests are received from clients and are assigned a port on the server. The <span style="color: blue;">default port</span> for nonsecure HTTP applications is kept as 8080 to avoid interference with any Web server running on the standard HTTP port, but there is no reason why this cannot be changed as long as the port is free. Multiple Connectors may be set up for a single Engine or Engine-level component, but they must have unique port numbers.</i></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The <span style="color: blue;">default port to which browsers make requests</span> if a port number is not specified is port 80. If Tomcat is run in standalone mode, the port for the primary Connector of the Web application can be changed to 80 by reconfiguring this component.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The default port to which browsers make requests if a port number is not specified is port 80. If Tomcat is run in standalone mode, the port for the primary Connector of the Web application can be changed to 80 by reconfiguring this component.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>HTTP Connector</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The HTTP Connector element represents a Connector component that supports the <span style="color: blue;">HTTP/1.1 protocol</span>. It enables <span style="color: blue;">Catalina </span>to function as a stand-alone web server, in addition to its ability to execute <span style="color: blue;">servlets </span>and <span style="color: blue;">JSP </span>pages. A particular instance of this component listens for connections on a specific TCP port number on the server. One or more such Connectors can be configured as part of a single Service, each forwarding to the associated Engine to perform request processing and create the response.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">If you wish to configure the Connector that is used for connections to web servers using the AJP protocol (such as the mod_jk 1.2.x connector for Apache 1.3), please refer to the AJP Connector documentation.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">All implementations of Connector support the following attributes:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">allowTrace : A boolean value which can be used to enable or disable the TRACE HTTP method. If not specified, this attribute is set to false.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">asyncTimeout : The default timeout for asynchronous requests in milliseconds. If not specified, this attribute is set to the Servlet specification default of 30000 (30 seconds).</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">enableLookups : Set to true if you want calls to request.getRemoteHost() to perform DNS lookups in order to return the actual host name of the remote client. Set to false to skip the DNS lookup and return the IP address in String form instead (thereby improving performance). By default, DNS lookups are disabled.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">maxHeaderCount</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">maxParameterCount</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">maxPostSize</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">maxSavePostSize</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">parseBodyMethods : A comma-separated list of HTTP methods for which request bodies will be parsed for request parameters identically to POST.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">port : The TCP port number on which this Connector will create a server socket and await incoming connections.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">protocol : Sets the protocol to handle incoming traffic</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">proxyName</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">proxyPort</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">redirectPort : If this Connector is supporting non-SSL requests, and a request is received for which a matching <security-constraint> requires SSL transport, Catalina will automatically redirect the request to the port number specified here.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">scheme</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">secure</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">URIEncoding</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">useBodyEncodingForURI</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">useIPVHosts</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">xpoweredBy</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><b>The standard HTTP connectors</b></span></div>
<div>
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">BIO</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">NIO</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">NIO2</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">APR/native</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><u>Special Featur</u>es</span></div>
</div>
<div>
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">HTTP/1.1 and HTTP/1.0 Support</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Proxy Support</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">SSL Support</span></li>
</ul>
</div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>Context</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Finally, there is the Web application, also known as a <b>context</b>. Configuration of a Web application includes informing the Engine/Hosts of the location of the root folder of the application.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Finally, there is the Web application, also known as a context. Configuration of a Web application includes informing the Engine/Hosts of the location of the root folder of the application.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">The context may also <span style="color: blue;">include specific error pages</span>, which enable a system administrator to configure error messages that are consistent with the look and feel of the application, and <span style="color: blue;">usability features</span> (such as a search Engine, useful links, or a report-creating component that notifies the administrator of errors in the application). Finally, a context can also be <span style="color: blue;">configured with initialization parameters</span> for the application it represents and for access control (authentication and authorization restrictions).</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The web application used to process each HTTP request is selected by Catalina based on matching the longest possible prefix of the Request URI against the context path of each defined Context. Once selected, that Context will select an appropriate servlet to process the incoming request, according to the servlet mappings defined by the web application deployment.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">You may define as many Context elements as you wish. Each such Context MUST have a unique context name within a virtual host. The context path does not need to be unique . In addition, a Context must be present with a context path equal to a zero-length string. This Context becomes the default web application for this virtual host, and is used to process all requests that do not match any other Context's context path.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Parallel deployment</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">You may deploy multiple versions of a web application with the same context path at the same time. The rules used to match requests to a context version are as follows:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">If no session information is present in the request, use the latest version.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">If session information is present in the request, check the session manager of each version for a matching session and if one is found, use that version.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">If session information is present in the request but no matching session can be found, use the latest version.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><b>Naming</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">When <span style="color: blue;">autoDeploy </span>or <span style="color: blue;">deployOnStartup </span>operations are performed by a Host, the name and context path of the web application are derived from the name(s) of the file(s) that define(s) the web application. Consequently, the context path may not be defined in a <span style="color: blue;">META-INF/context.xm</span>l embedded in the application and there is a close relationship between the context name, context path, context version and the base file name (the name minus any .war or .xml extension) of the file.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">If no version is specified then the context name is always the same as the context path. If the context path is the empty string them the base name will be ROOT (always in upper case) otherwise the base name will be the context path with the leading '/' removed and any remaining '/' characters replaced with '#'.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">If a version is specified then the context path remains unchanged and both the context name and the base name have the string '##' appended to them followed by the version identifier.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><b>Defining a context</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">It is NOT recommended to place <Context> elements directly in the server.xml file. This is because it makes modifying the Context configuration more invasive since the main conf/server.xml file cannot be reloaded without restarting Tomcat.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Individual Context elements may be explicitly defined:</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">In an individual file at /META-INF/context.xml inside the application files</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">In individual files (with a ".xml" extension) in the $CATALINA_BASE/conf/[enginename]/[hostname]/ directory</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">Inside a Host element in the main conf/server.xml.</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><span style="color: blue;">Default Context</span> elements may be defined that <span style="color: blue;">apply to multiple web applications</span>. Configuration for an individual web application will override anything configured in one of these defaults. Any nested elements, e.g. <Resource> elements, that are defined in a default Context will be created once for each Context to which the default applies. They will not be shared between Context elements.</span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">In the <span style="color: blue;">$CATALINA_BASE/conf/context.xml</span> file: the Context element information will be loaded by all web applications.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">In the <span style="color: blue;">$CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default</span> file: the Context element information will be loaded by all web applications of that host.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;">With the exception of server.xml, files that define Context elements may only define a single Context element.</span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<b><span style="font-family: Trebuchet MS, sans-serif; font-size: large;">The Valves</span></b><br />
<span style="font-family: Trebuchet MS, sans-serif;">This is how valves look like in server.xml</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-MoLQPZWpMlQ/VC5dU97GHyI/AAAAAAAAIPY/6L_m8C-6Nf8/s1600/valve_tomcat.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-MoLQPZWpMlQ/VC5dU97GHyI/AAAAAAAAIPY/6L_m8C-6Nf8/s1600/valve_tomcat.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Valves are components that e<span style="color: blue;">nable Tomcat to intercept a request and pre-process it</span>. They are<span style="color: blue;"> similar to the filter mechanism of the Servlet</span> specifications, but are specific to Tomcat. Hosts, contexts, and Engines may contain Valves</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Values are commonly <span style="color: blue;">used to enable Single Sign-on</span> for all Hosts on a server, as well as <span style="color: blue;">log request patterns</span>. client IP addresses ans <span style="color: blue;">server usage patterns</span> (peak traffic, bandwidth use, average request per unit time and so on). This is know as <b>request dumping</b>, and a <b>request dumper valve records</b> the header information and any cookies send with the request. Response dumpong logs the response header and cookies to file.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Valves are typically <span style="color: blue;">reusable components</span>, and can therefore be added and removed from the request path according to need. Their <span style="color: blue;">inclusion is transparent to Web applications</span>, although the response time will increase if a Valve is added). An application that wishes to intercept requests for pre-processing and responses for post-processing should use the filters that are a part of the Servlet specifications.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">A Valve may intercept a request between an Engine and a Host/context, between a Host and a context,and between a context and a resource within the Web application.</span><br />
<div>
<br /></div>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>The Realm</b></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-rer9TaScVHU/VC5flh_hPtI/AAAAAAAAIQA/GqY2kH0stYI/s1600/realm_tomcat.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-rer9TaScVHU/VC5flh_hPtI/AAAAAAAAIQA/GqY2kH0stYI/s1600/realm_tomcat.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The Realm for an Engine <span style="color: blue;">manages user authentication and authorization</span>. During the configuration of an application, the <span style="color: blue;">administrator sets the roles</span> that are allowed for each resource or group of resources, and the Realm is used to enforce this policy.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><i>Realms can authenticate against text files, database tables, LDAP servers, and the Windows network identity of the user</i></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">A Realm applies across the entire Engine or top-level container, so applications within a container share user resources for authentication. This means that, for example, a manager for the intranet will have the same rights as the manager of the e-commerce site should both these applications be in the same Engine.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;">By default, a user must still authenticate separately to each Web application on the server.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.2000007629395px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com10tag:blogger.com,1999:blog-5855689509747625696.post-63018841130982224532014-09-05T23:12:00.001+05:302014-09-06T19:27:18.438+05:30Difference between object reference variables and primitive variables in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="font-family: Trebuchet MS, sans-serif;">Java has two types of variables such as primitive and references variable and understanding of them are the very necessary who has just started learning Java. In this post, we'll into the difference between them and how they are use in Java.</span><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;">
<a href="http://4.bp.blogspot.com/-y19_-u_f7Ns/VAn2uzs2jhI/AAAAAAAAIGw/xTJhNia8Fus/s1600/reference%2Bvariables%2Bvs%2Bprimitive%2Bvariables.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-y19_-u_f7Ns/VAn2uzs2jhI/AAAAAAAAIGw/xTJhNia8Fus/s1600/reference%2Bvariables%2Bvs%2Bprimitive%2Bvariables.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">The variables in Java can be categorized into two types: <span style="color: blue;">primitive</span> variables and <span style="color: blue;">reference </span>variables</span><br />
<br />
<ul style="text-align: left;">
<li><b style="font-family: 'Trebuchet MS', sans-serif;">Primitives </b><span style="font-family: 'Trebuchet MS', sans-serif;">A primitive can be one of eight types: char, boolean, byte, short, int, long, double, or float. Once a primitive has been declared, its primitive type can never change, although in most cases its value can change</span></li>
<li><b style="font-family: 'Trebuchet MS', sans-serif;">Reference variables</b><span style="font-family: 'Trebuchet MS', sans-serif;"> A reference variable is used to refer to (or access) an object. A reference variable is declared to be of a specific type and that type can never be changed. A reference variable can be used to refer to any object of the declared type, or of a subtype of the declared type (a compatible type)</span></li>
</ul>
<br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b>What are object reference variables?</b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Objects are instances of classes, including both predefined and user-defined classes. For a reference type in Java, the v<span style="color: blue;">ariable name evaluates to the address of the location in memory</span> where the<span style="color: cyan;"> </span><span style="color: blue;">object referenced by the variable is stored</span>. An object reference is, in fact, a memory address that points to a memory area where an object’s data is located.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Let’s define a class, Person, as follows:</span><br />
<span style="color: blue; font-family: Trebuchet MS, sans-serif;"><i>class Person { }</i></span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">When an object is instantiated with the new operator, a heap-memory address value to that object is returned. That address is usually assigned to the reference variable</span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-A8hbIbEPoUg/VAntcQkkMKI/AAAAAAAAIEU/bpk1Zv2ifTs/s1600/referecen_variable_creation_in_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-A8hbIbEPoUg/VAntcQkkMKI/AAAAAAAAIEU/bpk1Zv2ifTs/s1600/referecen_variable_creation_in_java.png" height="178" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-tExfPmSHxls/VAntuSRvRII/AAAAAAAAIEc/pGRbHS16KU8/s1600/referecen_variable_in_memory_in_java.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-tExfPmSHxls/VAntuSRvRII/AAAAAAAAIEc/pGRbHS16KU8/s1600/referecen_variable_in_memory_in_java.png" height="376" width="640" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><u>When the statement shown in figure executes, three things happen:</u></span><br />
<br />
<ul style="text-align: left;">
<li><span style="font-family: Trebuchet MS, sans-serif;">A new Person object is created.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">A variable named person is created in the stack with an empty (null) value.</span></li>
<li><span style="font-family: Trebuchet MS, sans-serif;">The variable person is assigned the memory address value where the object is located.</span></li>
</ul>
<div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span></div>
<br />
<span style="font-family: Trebuchet MS, sans-serif; font-size: large;"><b><span style="color: blue;">Reference variables </span>v/s<span style="color: blue;"> Primitive variables</span></b></span><br />
<span style="font-family: Trebuchet MS, sans-serif;">Just as men and women are fundamentally different (according to John Gray, author of <span style="color: #351c75;">M<i>en Are from Mars, Women Are from Venus</i></span>), primitive variables and object reference variables differ from each other in multiple ways. The <span style="color: blue;">basic difference</span> is that primitive variables store the actual values, whereas reference variables store the addresses of the objects they refer to.</span><br />
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;">Let’s assume that a class Person is already defined. If you create an int variable a, and an object reference variable person, they will store their values in memory</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-zwDIXHJ8lEI/VAnuXcZ7eFI/AAAAAAAAIEo/l7mYMwjnsuU/s1600/reference_vs_primitive_variable_in_java_0.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-zwDIXHJ8lEI/VAnuXcZ7eFI/AAAAAAAAIEo/l7mYMwjnsuU/s1600/reference_vs_primitive_variable_in_java_0.png" height="380" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-Cu7C4A04lTs/VAnwbkw0pzI/AAAAAAAAIFo/bWCb-w60vxM/s1600/reference_vs_primitive_variable_in_java_1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-Cu7C4A04lTs/VAnwbkw0pzI/AAAAAAAAIFo/bWCb-w60vxM/s1600/reference_vs_primitive_variable_in_java_1.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-YV2ON1sIv4g/VAnwwEcljNI/AAAAAAAAIFw/BZDTP8OfrCE/s1600/reference_vs_primitive_variable_in_java_2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-YV2ON1sIv4g/VAnwwEcljNI/AAAAAAAAIFw/BZDTP8OfrCE/s1600/reference_vs_primitive_variable_in_java_2.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-LVvM70w3uuQ/VAnw-j30XRI/AAAAAAAAIF4/RoT3UrZo9gA/s1600/reference_vs_primitive_variable_in_java_3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-LVvM70w3uuQ/VAnw-j30XRI/AAAAAAAAIF4/RoT3UrZo9gA/s1600/reference_vs_primitive_variable_in_java_3.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-Nb0dsJTxXHU/VAnxTcQLy5I/AAAAAAAAIGA/zVVj1tRFVxw/s1600/reference_vs_primitive_variable_in_java_4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-Nb0dsJTxXHU/VAnxTcQLy5I/AAAAAAAAIGA/zVVj1tRFVxw/s1600/reference_vs_primitive_variable_in_java_4.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-uKK4UDRTh6s/VAnxkLUboSI/AAAAAAAAIGI/4EbzvortF7k/s1600/reference_vs_primitive_variable_in_java_5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-uKK4UDRTh6s/VAnxkLUboSI/AAAAAAAAIGI/4EbzvortF7k/s1600/reference_vs_primitive_variable_in_java_5.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-TWN0u1t464g/VAnyCR4UjII/AAAAAAAAIGQ/vGcuvyI-6us/s1600/reference_vs_primitive_variable_in_java_6.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-TWN0u1t464g/VAnyCR4UjII/AAAAAAAAIGQ/vGcuvyI-6us/s1600/reference_vs_primitive_variable_in_java_6.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-j9mdZ--wkxc/VAnyT0VfX2I/AAAAAAAAIGY/DPe_0rKyK_A/s1600/reference_vs_primitive_variable_in_java_7.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-j9mdZ--wkxc/VAnyT0VfX2I/AAAAAAAAIGY/DPe_0rKyK_A/s1600/reference_vs_primitive_variable_in_java_7.png" /></a></div>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<span style="font-family: Trebuchet MS, sans-serif;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<span style="background-color: white; color: blue; font-family: 'Trebuchet MS', sans-serif; font-size: 13px; line-height: 18.200000762939453px;">If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...</span></div>
Pardeep kumarhttp://www.blogger.com/profile/15415177669352479825noreply@blogger.com2