Friday, December 26, 2014

String pool concept in Java

String 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.
You can create objects of the class String by using the new operator, by using the assignment operator ( = ), or by enclosing a value within double quotes ( " ). But you may have noticed a big difference in how these objects are created, stored, and referred by Java.

Let’s create two String objects with the value "JavaLatte" using the operator new :

This image illustrates the previous code.

In the previous code, a comparison of the String reference variables str1 and str2 prints false . The operator == compares the addresses 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 stored at separate locations.


Let’s create two String objects with the value "Latte" using the assignment operator ( = ). 
The variables str3 and str4 and the objects referred to by these variables
In the previous example, the variables str1 and str2 referred to different String objects, even if they were created using the same sequence of characters. In the case of variables str3 and str4, the objects are created and stored in a pool of String objects. Before creating a new object in the pool, Java first searches for an object with similar contents.

When the following line of code executes, no String object with the value "Latte" is found in the pool of String objects:
String str3 = "Latte";
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
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:
String str4 = "Latte";



Java doesn’t create a new String object in this case, and the variable str4 refers to the existing String object "Latte".


You can also create a String object by enclosing a value within double quotes ( " ):


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:

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:

The preceding code shows that object references of String objects that exist in the String constant pool and object references of String objects that don’t exist in the String constant pool don’t refer to the same String object, even if they define the same String value.

Where String pool is stored in memory

  • Java 6
    Permanent Generation 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

  • Java 7
    The string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings 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
Note strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Use of String intern() method
Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) 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.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.

String allocation, like any other object creation proves costly in time and memory.The JVM do some trickery while instantiating the string literals to increase performance and decrease memory 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.


If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Monday, December 22, 2014

ClassCastException in Java

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.


ClassCastException 
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:
Object x = new Integer(0);
System.out.println((String)x);

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.

ClassCastException is thrown when 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 tries to explicitly cast an object of ColorInk to BlackInk.


Why above code avoided the compilation error
Note that above line of code avoided the compilation error because the variable inks defines an ArrayList of type Ink , which is capable of storing objects of type Ink and all its subclasses. The code then correctly adds the allowed objects: one each of BlackInk and ColorInk.

If the code had defined an ArrayList of type BlackInk or ColorInk , the code would have failed the compilation, as follows:
Here’s the compilation error thrown by the previously modified piece of code:

How to avoid ClassCastException
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?
Yes, this will work and the program will not crash. But this is a really bad idea! There are two main problems in this code.

  • Providing exception handlers for RuntimeExceptions like this create an illusion that the program is working perfectly fine, when it is not!
  • Runtime exceptions like ClassCastException indicate programming errors and should not be caught using exception handlers.
Okay, so what do you do now? Before downcasting, check for the dynamic type of the object and then downcast. You can use the instanceof operator to verify whether an object can be cast to another class before casting it.

This is an effective and proper way to achieve downcasting. Using the instanceof operator checks the dynamic type of obj, which helps you to decide whether to downcast it to a String object.

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 following lines of code will avoid the ClassCastException

In the previous example, the condition ( inks.get(0)instanceofBlackInk ) evaluates to false , so the then part of the if statement doesn’t execute.


Question
Try to examine and share the output of the following program in comment section




If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, November 23, 2014

Finding superclasses of an object in Java

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 enables what is commonly referred to as dynamic programming in Java. Reflection in Java is accomplished using the Java Reflection API



Reflection 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.

Finding Superclasses
The ancestors of a given class are referred to as that class’s superclasses. Using reflection, you can determine all of the ancestors of a given class. After you've obtained a Class object, you can use the getSuperclass() 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 Java supports only single inheritance, so for any given class, there can be only one superclass.  Actually to be clear, there can be only one direct superclass.Technically, 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.

Here is an example, that explain the above concept 

Example 2 In this example, we try to find the super classes of BigDecimal class. 

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Saturday, November 1, 2014

Implicit Objects In JSP

JavaServer Pages (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 9 implicit object of JSP with explanation and examples.

In a web application, multiple web components collaborate with each other and share information by means of objects that are maintained as attributes of four scope objects. You access these attributes by using the getAttribute and setAttribute methods of the class representing the scope

Note In addition to the standard servlet request, session, and application scopes, JSP adds a fourth scope called page scope.


A JSP page can access some specific objects through scripting variables. These objects are provided by the JSP container and are called implicit objects. These implicit objects can be accessed in scriptlets, in expressions, or as part of the EL expressions.



  • application
    The implicit application object provides a reference to the javax.servlet.ServletContext interface. The ServletContext 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.
    In short, application provides access to web context. Its use is similar to that of ServletContext.
  • config
    Similar to the application object, the config object provides a reference to the ServletConfig 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.
    In short, config provides initialization information used by the JSP container. Its use is similar to that of the class ServletConfig.
  • exception
    The implicit exception object is available to JSP to handle the error conditions and report the runtime exceptions using the errorPage page directive. Exception represents an instance of the Throwable object and contains error information. This variable is available only from the JSP error page
  • out
    The implicit out object represents an instance of the JspWriter 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 HttpServletResponse.getWriter() in servlets. For example, a simplest JSP that returns a result from a Java class called CurrencyConverter might look like this
    <html>
       <body>
         <% out.println(CurrencyConverter.getDollarRate()); %>
       </body>
    </html>
  • page
    The JSP implicit page object is an instance of the Object class and represents the current JSP page. In short, page represents the instance of the JSP’s servlet.
  • pageContext
    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 implicit objects. pageContext represents the JSP context and is used with Tag Libraries
  • request
    The request object is an instance of the javax.servlet.http.HttpServletRequest 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.
  • response
    The implicit response object is an instance of the javax.servlet.http.HttpServletResponse 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.
  • session
    The JSP implicit session object is an instance of a Java class that implements the javax.servlet.http.HttpSession interface. It is used to store session state for a client.



Examples of Common Implicit Objects

getServletContext().setAttribute("blog", JavaLatte);
This sets the book attribute in a ServletContext without using implicit objects.

request.setAttribute("blog", JavaLatte);
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.

request.getSession().setAttribute("book", book);
This sets the book attribute in the session without using implicit objects

application.setAttribute("book" book);
This sets the book attribute in the ServletContext using the application implicit object.

request.setAttribute("book" book);
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.

session.setAttribute("book" book);
This sets the book attribute in the session using a session implicit object

pageContext.setAttribute("book" book);
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.



If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Saturday, October 25, 2014

How Hibernate Works and it's Persistence Lifecycle

The main idea behind any ORM 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 POJO, assign values to its fields, and tell it “Persist yourself in the database.” 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.

Hibernate's primary feature is mapping from Java classes to database tables (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


Hibernate architecture
As you can see from following picture, how much of Hibernate you use depends on your needs. At its simplest level Hibernate provides a lightweight architecture that deals only with ORM. Full-blown usage of Hibernate fully abstracts most aspects of persistence, such as transaction, entity/query caching, and connection pooling.





How Hibernate Works
Hibernate’s success lies in the simplicity of its core concepts. At the heart of every interaction between your code and the database lies the Hibernate Session. Following image provides an overview of how Hibernate works and don't need any explanation if you have an idea about hibernate.





The heart of any Hibernate application 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
Let's see the basic introduction to all the component and there roles in hibernate.


Configure the Database Connection (.cfg.xml)
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 hibernate.cfg.xml) or as a simple text file with name/value pairs (usually named hibernate.properties).

In XML style. We name this file hibernate.cfg.xml so the framework can load this file automatically.
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 hibernate.cfg.xml file:

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 

hibernate.properties:

hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3307/JH
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

connection.url indicates the URL to which we should be connected, driver_class represents the relevant Driver class to make a connection, and the dialect 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 “hibernate” and follow a pattern—hibernate.* properties, for instance

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:


<hibernate-configuration>
 <session-factory>
 ...
 <mapping resource="table1.hbm.xml" />
 <mapping resource="table2.hbm.xml" />
 <mapping resource="table3.hbm.xml" />
 </session-factory>
</hibernate-configuration>


Create Mapping Definitions
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:

<hibernate-mapping>
 <class name="com.java.latte.table1" table="TABLE1">
 <id name="id" column="ID">
 <generator class="native"/>
 </id>
 <property name="title" column="TITLE"/>
 <property name="director" column="DIRECTOR"/>
 <property name="synopsis" column="SYNOPSIS"/>
 </class>

</hibernate-mapping>

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 com.java.latte.table1, while the table attribute refers to the table TABLE1 to which the objects are persisted.
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.


What does Hibernate do with this properties file?
The Hibernate framework loads this file to create a SessionFactory, 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 hibernate.hbm.xml to create a separate SessionFactory for that database too.

The goal of the SessionFactory is to create Session objects. Session is a gateway to our database. It is the Session’s job to take care of all database operations such as saving, loading, and retrieving 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.

Keep in mind that the configuration is used to create a Session via a SessionFactory instance. Before we move on, note that Session objects are not thread-safe and therefore should not be shared across different classes.


The Hibernate Session
The Hibernate Session embodies the concept of a persistence service (or persistence manager) that can be used to query and perform insert, update, and delete operations on instances of a class mapped by Hibernate. In an ORM tool you perform all of these interactions using object oriented semantics; that is, you no longer are referring to tables and columns, but you use Java classes and object properties. As its name implies, the Session is a short-lived, lightweight object used as a bridge during a conversation between the application and the database. 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.

The Session Factory
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 configuration files, along with the associated class mappings, are compiled and cached by the SessionFactory, which is used to retrieve Hibernate Sessions. The SessionFactory is a heavyweight object that should ideally be created only once (since it is an expensive and slow operation) and made available to the application code that needs to perform persistence operations

Each SessionFactory is configured to work with a certain database platform by using one of the provided Hibernate dialects. 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 org.hibernate.dialect


The Hibernate Object Mappings
Hibernate specifies how each object state is retrieved and stored in the database via an XML configuration file. Hibernate mappings are loaded at startup and are cached in the SessionFactory. Each mapping specifies a variety of parameters related to the persistence lifecycle of instances of the mapped class such as:

  • Primary key mapping and generation scheme
  • Object-field-to-table-column mappings
  • Associations/Collections
  • Caching settings
  • Custom SQL, store procedure calls, filters, parameterized queries, and more


Persistence Lifecycle of Hibernate
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.

In the transient state, the object is not associated with a database table. That is, its state has not been saved to a table, and the object has no associated database identity (no primary key has been assigned). Objects in the transient state are non-transactional, meaning that they do not participate in the scope of any transaction bound to a Hibernate Session. After a successful invocation of the save or saveOrUpdate methods an object ceases to be transient and becomes persistent. The Session delete method (or a delete query) produces the inverse effect making a persistent object transient.

Persistent objects 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 transactional, which means that they participate in transactions associated with the Session (at the end of the transaction the object state will be synchronized with the database).

A persistent object that is no longer in the Session cache (associated with the Session) becomes a detached object. This happens after a transaction completes, when the Session is closed, cleared, or if the object is explicitly evicted from the Session cache. 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).

I believe this has cleared you concept of how hibernate works and its components.


If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Thursday, October 23, 2014

NIO (New Input/Output) vs IO (Input/Output) and NIO.2 in Java

Non-blocking I/O (usually called NIO, 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 NIO2, was released with Java SE 7. In this article, we understand the concept of NIO and how is it useful as compare to IO (java.io.*). 




What Is Input/Output
Input/output (I/O) deals with reading data from a source and writing data to a destination. Data is read from the input source (or simply input) and written to the output destination (or simply output). For example, your keyboard works as a standard input, letting you read data entered using the keyboard into your program. You have been using the System.out.println() method to print text on the standard output from the very first Java program without your knowledge that you have been performing I/O.
The java.io and java.nio (nio stands for New I/O) packages contain Java classes that deal with I/O. The java.io package has an overwhelming number of classes 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 class explosion and the java.io package is a good example of that.

Input/Output Streams
The literal meaning of the word stream is "an unbroken flow of something." 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.

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 data source to a destination known as a data sink
The data is read from a data source to a Java program. A Java program writes data to a data sink. The stream that connects a data source and a Java program is called an input stream. The stream that connects a Java program and a data sink is called an output stream
In a natural stream, such as a river, the source and the destination are connected through the 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.
How we work with input/output stream

To read data from a data source into a Java program, you need to perform the following steps:

  • Identify the data source. It may be a file, a string, an array, a network connection, etc.
  • Construct an input stream using the data source that you have identified.
  • 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.
  • 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
To write data to a data sink from a Java program, you need to perform the following steps:

  • 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.
  • Construct an output stream using the data sink that you have identified.
  • Write the data to the output stream.
  • 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.

Input/output stream classes in Java are based on the decorator pattern.


What Is NIO?
The stream-based I/O uses streams to transfer data between a data source/sink and a Java program. The Java program reads from or writes to a stream a byte at a time. This approach to performing I/O operations is slow. The New Input/Ouput (NIO) solves the slow speed problem in the older stream-based I/O.
In NIO, you deal with channels and buffers for I/O operations. A channel is like a stream. It represents a connection between a data source/sink and a Java program for data transfer. 
There is one difference between a channel and a stream

  • A stream can be used for one-way 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. 
  • However, a channel provides a two-way data transfer facility. 

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.

In stream-based I/O, the basic unit of data transfer is a byte. In channel-based NIO, the basic unit of data transfer is a buffer.
A buffer is a bounded data container. That is, a buffer has a fixed capacity that determines the upper limit of the data it may contain. In stream-based I/O, you write data directly to the stream. In channel-based I/O, you write data into a buffer; 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 most important parts in this interaction are reading from a buffer and writing into a buffer.

New Input/Output 2 (NIO.2)
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: java.nio.file, java.nio.file.attribute, and java.nio.file.spi. The following are some of the new features of NIO.2:

  • It lets you deal with all file systems 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.
  • It supports basic file operations (copy, move, and delete) on all file systems. It supports an atomic file move operation. It has improved exception handling support.
  • It has support for symbolic links. Whenever applicable, operations on a symbolic link are redirected to the target file.
  • One of the most important additions to NIO.2 is the support for accessing the attributes of file systems and files.
  • It lets you create a watch service to watch for any events on a directory 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.
  • It added an API that lets you walk through a file tree. You can perform a file operation on a node as you walk through the file tree.
  • It supports asynchronous I/O on network sockets and files.
  • It supports multicasting using a DatagramChannel.


I hope this article has covered the basic introduction to NIO2 and how it differ from IO.


If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Wednesday, October 22, 2014

How to Join Threads in Java

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 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.



I will Join You in Heaven
I can rephrase this section heading as "I will wait until you die." That’s right. A thread can wait for another thread to die (or terminate).
Suppose 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 useful if one of the threads cannot proceed until another thread has finished executing.

An example where you want to print a message on the standard output when the program has finished executing. The message to print is "Printing Done."
Output:
Printing Done
Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4


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. What is wrong with this program?

The JVM starts a new thread called main that is responsible for executing the main() method of the class that you run. In your case, the main() method of the JoinWrong class is executed by the main thread
When the t1.start() method call returns, 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 "Printing Done." Since there are two threads responsible for two different tasks, it is not guaranteed which task will finish first. What is the solution? You must make your main thread wait on the thread t1 to terminate. This can be achieved by calling the t1.join() method inside the main() method.


Following example 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.
Output:
Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Printing Done


Java provides two additional forms of the join() method:

  • join (long milliseconds)
  • join (long milliseconds, long nanos)

In the first version of the join() method, instead of waiting indefinitely for the finalization of the thread called, the calling thread waits for the milliseconds specified as a parameter of the method. .
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:

  • thread2 finishes its execution
  • 1000 milliseconds have been passed
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.


Can a thread join multiple threads? The answer is yes. A thread can join multiple threads like so:
t1.join(); // Join t1
t2.join(); // Join t2
t3.join(); // Join t3

You should call the join() method of a thread after it has been started. 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.


This example 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.

Output:
Beginning data source loading at : Wed Oct 22 12:14:57 IST 2014
Beginning Network connection loading at : Wed Oct 22 12:14:57 IST 2014
Beginning data source loading finished at : Wed Oct 22 12:15:01 IST 2014
Beginning Network connection finished at : Wed Oct 22 12:15:03 IST 2014
Configuration has loaded

How it works...
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.




If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...