Wednesday, 26 October 2016

Java Source World: Multithreading - Joining threads | Join() method | how Join() method works


How Join() method works in Multithreaded environment:


Multithreading - Joining threads | Join() method | how Join() method works | Java Source World
Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join() are two different methods to check whether a thread has finished its execution.


The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false.

Syntax:  final boolean isAlive()


But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is called terminates.

Syntax:  final void join() throws InterruptedException


Using join() method, we tell our thread to wait until the specified thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.     

Syntax:  final void join(long milliseconds) throws InterruptedException

Example:

package com.core.alljavaconcepts.multithreading;

public class JoinExample {//Main class
      public static void main(String[] args) {
            Thread th1 = new Thread(new MyClass(), "Thread1");
            Thread th2 = new Thread(new MyClass(), "Thread2");
            //start first thread
            th1.start();
            //Start second thread once th1 is dead
            try {
                  th1.join();
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
            //start second thread
           
            //Display below message once the th2 is dead
            try {
                  th2.join();
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
            System.out.println("Threads completed");
      }  
}
class MyClass implements Runnable{
      @Override
      public void run() {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+" Strated ");
           
            try {
                  t.sleep(4000);
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
            System.out.println(t.getName()+" Ended ");
            System.out.println("------------------------");
      }
     
}
As per above example, first the thread one th1 starts its execution, and once after it completes its execution only the second thread th2 will start exeuting and completes the execution and displayes the last statement.

Lets see the out put of the above example code: 
That is as fallows:

Console out put:

Thread1 Strated 
Thread1 Ended 
------------------------
Thread2 Strated 
Thread2 Ended 
------------------------
Threads completed






You may also like the fallowing posts:




Read More »

Java Source World: Core java - How HashMap works in Java






How HashMap works in Java:


The 3 things you should know about hashCode():



In Java, every object has a method hashCode that is simple to understand but still it’s sometimes forgotten or misused. Here are three things to keep in mind to avoid the common pitfalls.

An object’s hash code allows algorithms and data structures to put objects into compartments, just like letter types in a printer’s type case. The printer puts all “A” types into the compartment for “A”, and he looks for an “A” only in this one compartment. This simple system lets him find types much faster than searching in an unsorted drawer. That’s also the idea of hash-based collections, such as HashMap and HashSet.

In order to make your class work properly with hash-based collections and other algorithms that rely on hash codes, all hashCode implementations must stick to a simple contract.

The hashCode contract
The contract is explained in the hashCode method’s JavaDoc. It can be roughly summarized with this statement:

Objects that are equal must have the same hash code within a running process

Please note that this does not imply the following common misconceptions:

Unequal objects must have different hash codes – WRONG!
Objects with the same hash code must be equal – WRONG!

The contract allows for unequal objects to share the same hash code, such as the “A“ and “µ” objects in the sketch above. In math terms, the mapping from objects to hash codes doesn’t have to be injective or even bijective. This is obvious because the number of possible distinct objects is usually bigger than the number of possible hash codes (232).

This contract directly leads to the first rule: 
1. Whenever you implement equals, you MUST also implement hashCode:

If you fail to do so, you will end up with broken objects. Why? An object’shashCode method must take the same fields into account as its equals method. By overriding the equals method, you’re declaring some objects as equal to other objects, but the original hashCode method treats all objects as different. So you will have equal objects with different hash codes. For example, calling contains() on a HashMap will return false, even though the object has been added.
How to write a good hashCode function is beyond the scope of this article, it is perfectly explained in Joshua Bloch’s popular book Effective Java, which should not be missing in a Java developer’s bookshelf.

HashCode collisions
Whenever two different objects have the same hash code, we call this a collision. A collision is nothing critical, it just means that there is more than one object in a single bucket, so a HashMap lookup has to look again to find the right object. A lot of collisions will degrade the performance of a system, but they won’t lead to incorrect results.
But if you mistake the hash code for a unique handle to an object, e.g use it as a key in a Map, then you will sometimes get the wrong object. Because even though collisions are rare, they are inevitable. For example, the Strings "Aa" and "BB" produce the same hashCode: 2112.

2. Never misuse hashCode as a key

You may object that, unlike the printer’s type case, in Java there are 4,294,967,296 compartments (232 possible int values). With 4 billion slots, collisions seem to be extremely unlikely, right?
Turns out that it’s not so unlikely. Here’s the surprising math of collisions: Please imagine 23 random people in a room. How would you estimate the odds of finding two fellows with the same birthday among them? Pretty low, because there are 365 days in a year? In fact, the odds are about 50%! And with 50 people it’s a save bet. This phenomenon is called theBirthday paradox. Transferred to hash codes, this means that with 77,163 different objects, you have a 50/50 chance for a collision – given that you have an ideal hashCode function, that evenly distributes objects over all available buckets.

The Enron email dataset contains 520,924 emails. Computing the Stringhash codes of the email contents, I found 50 pairs (and even 2 triples) of different emails with the same hash code. For half a million strings, this is a pretty good result. But the message here is: if you have many data items, collisions will occur. If you were using the hashCode as a key here, you would not immediately notice your mistake. But a few people would get the wrong mail.

HashCodes can change

Finally, there’s one important detail in the hashCode contract that can be quite surprising: hashCode does not guarantee the same result in different executions. Let’s have a look at the JavaDoc:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCodemethod must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
This is uncommon, in fact, some classes in the class library even specify the exact formula they use to calculate hash codes (e.g. String). For these classes, the hash code will always be the same. But while most of thehashCode implementations provide stable values, you must not rely on it. As this article points out, there are Java libraries that actually return different hashCode values in different processes and this tends to confuse people. Google’s Protocol Buffers is an example.

Therefore, you should not use the hash code in distributed applications. A remote object may have a different hash code than a local one, even if the two are equal.

3. Do not use hashCode in distributed applications
Moreover, you should be aware that the implementation of a hashCodefunction may change from one version to another. Therefore your code should not depend on any particular hash code values. For example, your should not use the hash code to persist state. Next time you run the application, the hash codes of the “same” objects may be different.
The best advice is probably: don’t use hashCode at all, except when you create hash-based algorithms.

An alternative: SHA1
You may know that cryptographic hash codes such as SHA1 are sometimes used to identify objects (Git does this, for example). Is this also unsafe? No. SHA1 uses 160-bit keys, which makes collisions virtually impossible. Even with a gigantic number of objects, the odds of a collision in this space are far below the odds of a meteor crashing the computer that runs your program.

There’s probably more to say about hash codes, but these seem to be the most important things. If there’s anything I’ve missed, I’m happy to hear about it!



You may like the fallowing posts:



                                                           Java Source World                         A Java quick reference blog


Read More »

Java Source World: ConcurrentModificationException when using an iterator

ConcurrentModificationException when using an iterator | Java Source World

                                                                                                               Java Source World A Java quick reference blog



How to avoid concurrent modification exception in java


Problem: The java.util Collection classes are fail-fast, which means that if one thread changes a collection while another thread is traversing it through with an iterator the iterator.hasNext() or iterator.next() call will throw ConcurrentModificationException.



Even the synchronized collection wrapper classes SynchronizedMap and SynchronizedList are only conditionally thread-safe, which means all individual operations are thread-safe but compound operations where flow of control depends on the results of previous operations may be subject to threading issues.





package com.javaconcept.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ConcurrentModification {
      public static void main(String[] args) {
            Collection<String> myCollection = new ArrayList<String>(10);
            myCollection.add("123");
            myCollection.add("456");
            myCollection.add("789");
            for (Iterator it = myCollection.iterator(); it.hasNext();) {
            String myObject = (String)it.next();
            System.out.println(myObject);
            myCollection.remove(myObject); //can throw ConcurrentModificationException in single as
            //well as multi-thread access situations.
            }

      }
}

Solutions 1-3: for multi-thread access situation:

Solution 1: You can convert your list to an array with list.toArray() and iterate on the array. This approach is not recommended if the list is large.

Solution 2: You can lock the entire list while iterating by wrapping your code within a synchronized block. This approach adversely affects scalability of your application if it is highly concurrent.

Solution 3: If you are using JDK 1.5 then you can use the ConcurrentHashMap and CopyOnWriteArrayList classes, which provide much better scalability and the iterator returned by ConcurrentHashMap.iterator() will not throw ConcurrentModificationException while preserving thread-safety.

Solution 4: for single-thread access situation:
Use:
it.remove(); // removes the current object via the Iterator “it” which has a reference to
// your underlying collection “myCollection”. Also can use solutions 1-3.

Avoid:
myCollection.remove(myObject); // avoid by-passing the Iterator. When it.next() is called, can throw the exception // ConcurrentModificationException

Note: If you had used any Object to Relational (OR) mapping frameworks like Hibernate, you may have encountered this exception “ConcurrentModificationException” when you tried to remove an object from a collection such as a java.util Set with the intention of deleting that object from the underlying database. This exception is not caused by Hibernate but rather caused by your java.util.Iterator (i.e. due to your it.next() call). You can use one of the solutions given above.



Other posts you may like:

How HashMap works in Java
Equals() and Hashcode() in java
Serialization in java

                                                                                                                Java Source World A Java quick reference blog



Read More »

Tuesday, 25 October 2016

Java Source World: Spring Framework - Constructor Injection with Collection Example


Constructor Injection with Collection Example


  • We can inject collection values by constructor in spring framework.
  • There can be used three elements inside the constructor-arg element. 

It can be: 
  1.  list 
  2.  set
  3.  map
Each collection can have string based and non-string based values.
In this example, we are taking the example of Forum where One question can have multiple answers. There are three pages:
  1.     Question.java
  2.     applicationContext.xml
  3.     Test.java
In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
Question.java

This class contains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.

    package com.springexample; 

    import java.util.Iterator; 
    import java.util.List; 
    
    public class Question { 
    private int id; 
    private String name; 
    private List<String> answers; 
   public Question() {} 
    public Question(int id, String name, List<String> answers) { 
        super(); 
        this.id = id; 
        this.name = name; 
        this.answers = answers; 
    }       
    public void displayInfo(){ 
        System.out.println(id+" "+name); 
        System.out.println("answers are:"); 
        Iterator<String> itr=answers.iterator(); 
        while(itr.hasNext()){ 
            System.out.println(itr.next()); 
        }    }  } 
applicationContext.xml

The list element of constructor-arg is used here to define the list.

    <?xml version="1.0" encoding="UTF-8"?> 
    <beans 
        xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:p="http://www.springframework.org/schema/p" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
    <bean id="q" class="com.springexample.Question"> 
    <constructor-arg value="111"></constructor-arg> 
    <constructor-arg value="What is java?"></constructor-arg> 
    <constructor-arg> 
    <list> 
    <value>Java is a programming language</value> 
    <value>Java is a Platform</value> 
    <value>Java is an Island of Indonasia</value> 
    </list> 
    </constructor-arg> 
    </bean>   
    </beans> 

Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo method.
    package com.springexample; 

    import org.springframework.beans.factory.BeanFactory; 
    import org.springframework.beans.factory.xml.XmlBeanFactory; 
    import org.springframework.core.io.ClassPathResource; 
    import org.springframework.core.io.Resource; 
    

    public class Test { 
    public static void main(String[] args) { 
        Resource r=new ClassPathResource("applicationContext.xml"); 
        BeanFactory factory=new XmlBeanFactory(r); 
         
        Question q=(Question)factory.getBean("q"); 
        q.displayInfo(); 
         
    } 
    }  



Read More »