Thursday, 19 February 2015

Immutable Class Example in Java

public final class ImmtableClass {

    private final String name;
    private final String mobile;

    public ImmtableClass(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
}

This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case. Some time you may need to write immutable class which includes mutable classes likejava.util.Date, despite storing Date into final field it can be modified internally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice. here is another example of making a class immutable in Java, which includes mutable member variable.

--------------------------------------------------------------------------

Benefits of Immutable Classes in Java

As I said earlier Immutable classes offers several benefits, here are few to mention:

1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.

3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers.  You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.

Apart from above advantages, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection, but again that's extreme case and if used properly Immutable object adds lot of value.

That's all on how to write immutable class in Java. we have seen rules of writing immutable classes, benefits offered by immutable objects and how we can create immutable class in Java which involves mutable fields. Don’t forget to read more about concurrency benefit offered by Immutable object in one of the best Java book recommended to Java programmers, Concurrency Practice in Java.


Reference:---

Read more: http://javarevisited.blogspot.com/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html#ixzz3SCrNlzyn

--------------------------------------------

5 ways to Reverse a String in Java with Example


Monday, 16 February 2015

MultiThreading Example:-Using single application for more


package com.bsl.model;
class TestMultiNaming1 extends Thread{
    static int a, b, c;
 public void run(){
   
     if(Thread.currentThread().getName().equalsIgnoreCase("addition"))
     {
        a= m1();
     System.out.println("addition done"+a+"reading of file done here");
       
         }
     if(Thread.currentThread().getName().equalsIgnoreCase("multiply"))
     {
        b= m2();
             System.out.println("multiply done"+b+"file has been pasted to someother location");
         }
     if(Thread.currentThread().getName().equalsIgnoreCase("equal"))
     {
             c=a+b;  System.out.println("total done"+c);      
         }
 }
 int m1(){
     System.out.println("addition");
    return 9;}
    int m2(){
        System.out.println("multiply");
       return 4;}
    int tt(){
        System.out.println("total");
       return 9;}
public static void main(String args[]){
 TestMultiNaming1 t1=new TestMultiNaming1();
 TestMultiNaming1 t2=new TestMultiNaming1();
 TestMultiNaming1 t3=new TestMultiNaming1();
 t1.setName("addition");
 t2.setName("Multiply");
 t3.setName("equal");
 t1.start();

 try{
  t1.join();
     t2.start();
     t2.join();
   
 }catch(Exception e){System.out.println(e);}
 t3.start();
 }
}  

Sunday, 15 February 2015

Best Of Collection Question In Java.


Differences between HashSet and HashMap in Java
HashSet internally uses HashMap to store objects.when add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy).so it maintain no duplicates because keys are nothing but Value Object.
the Objects which are stored as key in Hashset/HashMap should override hashcode & equals contract.
Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.

How HashSet Internally Works in Java:-

http://java67.blogspot.in/2014/01/how-hashset-is-implemented-or-works-internally-java.html

------------------------------------------------------------------------------------------------------------------

How HashMap works in java

http://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html
 or
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html?_sm_au_=iVVq5Q1F10JH7NHN

http://javapapers.com/core-java/java-hashtable/
------------------------------------------------------------------------------------------------------------------

http://www.java2blog.com/2014/02/how-hashmap-works-in-java.html

http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html

Watching vedio must help you:-
https://www.youtube.com/watch?v=iinE6ZBNBjw
------------------------------------------------------------------------------------------------------------------

HashMap – Single Key and Multiple Values Example


http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
-----------------------------------------------------------------------------------------------------------------

How to add duplicate key in map:-

http://stackoverflow.com/questions/18922165/how-to-include-duplicate-keys-in-hashmap

if you want to do manually we can use this trick

 if ( ! map.containsKey( key ) ) {
            List list = new ArrayList( );
            list.add( value);
            map.put( key, list);
        }
        else {
            List list = (List) map.get(key);
            list.add( value );
        }

Or if you want to have a single list.add():
        if ( ! map.containsKey( key ) ) {
            List list = new ArrayList( );
            map.put( key, list);
        }
        
        List list = (List) map.get(key);
        list.add( value );
---------------------------------------------------------------------------------------

0r

http://java.dzone.com/articles/allowing-duplicate-keys-java

---------------------------------------------------------------------------------------------------

Why Use Inner Classes?

There are several compelling reasons for using nested classes, among them:
  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.
  • ---------------------------------------------------------------------
  • -One good usage of inner classes that comes into my mind is in java.util.ArrayList that hides its iterators implementations into private inner classes. You can't create them except by invoking iterator() or listIterator() on the list object.
    This way the Iterator and ListIterator implementations for ArrayList are grouped with their related class and methods for enhanced readability (the implementations are pretty short), but hidden from others.
----------------------------------------------------------------------------------------------------------------
Best of hash Code by Eclipse
http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/

-------------------------------------------------------------------------------------------------------------
ArrayList vs Linked List(when to use linked list)
http://beginnersbook.com/2013/12/difference-between-arraylist-and-linkedlist-in-java/
--------------------------------------------------------------------------------------------------------------

Monday, 9 February 2015

Best of Servlet Thread Safety:-

Servlet Concurrency:-

for more details look in below website:-
http://tutorials.jenkov.com/java-servlets/servlet-concurrency.html

Detailed Thread-Safety Questions concerning Java Servlets

  1. Your understanding is correct. Actually thread is created for each request. So HttpServletRequest and HttpServletResponse are local to thread. So no sharing of these two. You do not need to synchronize them. HttpServletRequestWrapper and HttpServletResponseWrapper are the classes which provide a convenient implementation of the HttpServletRequest and HttpServletResponse interfaces respectively. You do not need to worry about them in synchronization context.
  2. Definitely you have to provide synchronization for ServletContext object returned by getServletContext() because it is shared between servlets in your application.
  3. As HttpServletRequest is local to thread created by container to serve the request. So cookies are also local to that thread and those are not shared. So no need to provide synchronization to cookies.
Few concepts :
  1. Servlets are always singlton in your application. i.e. only one object is created.
  2. For each request a different thread is created(actually obtained from Thread Pool). Following things are local to thread : HttpServletRequest, HttpServletResponse
Reference:-

Is HttpSession is ThreadSafe:-

Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a threadsafe manner. The Developer has the responsibility for threadsafe access to the attribute objects themselves. This will protect the attribute collection inside the HttpSession object from concurrent access, eliminating the opportunity for an application to cause that collection to become corrupted.
This is safe:
// guaranteed by the spec to be safe
request.getSession().setAttribute("foo", 1);
This is not safe:
HttpSession session = request.getSession();
Integer n = (Integer) session.getAttribute("foo");
// not thread safe
// another thread might be have got stale value between get and set
session.setAttribute("foo", (n == null) ? 1 : n + 1);
This is not guaranteed to be safe:
// no guarantee that same instance will be returned,
// nor that session will lock on "this"
HttpSession session = request.getSession();
synchronized (session) {
  Integer n = (Integer) session.getAttribute("foo");
  session.setAttribute("foo", (n == null) ? 1 : n + 1);
}
I have seen this last approach advocated (including in J2EE books), but it is not guaranteed to work by the Servlet specification. You could use the session ID to create a mutex, but there must be a better approach.
Reference:-

How do servlets work? Instantiation, session variables and multithreading

please read the comment from stackoverflow:-

When the servletcontainer (like Apache Tomcat) starts up, it will deploy and load all webapplications. When a webapplication get loaded, the servletcontainer will create the ServletContext once and keep in server's memory. The webapp's web.xml will be parsed and every Servlet, Filter and Listener found in web.xml or annotated with respectively @WebServlet, @WebFilter and @WebListener will be created once and kept in server's memory as well. When the servletcontainer shuts down, it will unload all webapplications and the ServletContext and all Servlet, Filter and Listener instances will be trashed.
http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909

-------------------------------------------------------
http://stackoverflow.com/questions/2183974/difference-between-each-instance-of-servlet-and-each-thread-of-servlet-in-servle/2184147#2184147

http://www.javaworld.com/article/2072798/java-web-development/write-thread-safe-servlets.html

Sunday, 8 February 2015

What is the importance of "Charsequence" in java


Java CharSequence is an interface. As the API says, CharSequence has been implemented in CharBuffer, Segment, String, StringBuffer, StringBuilder classes. So if you want to access or accept your API from all these classes thenCharSequence is your choice. If not then String is very good for a public API because it is very easy & everybody knows about it. Remember CharSequence only gives you 4 method, so if you are accepting a CharSequence object through a method, then your input manipulation ability will be limited.
-----------------------------------------------------------------------------------------------------
It's just re factored from any existing implementations. One of the benefits is that you can "widen" the input whenever you actually only need one of its methods.
So instead of for example
public void printEveryChar(String string) {
    for (int i = 0; i < string.length(); i++) {
        System.out.println(string.charAt(i));
    }
}
you can have
public void printEveryChar(CharSequence charSequence) {
    for (int i = 0; i < charSequence.length(); i++) {
        System.out.println(charSequence.charAt(i));
    }
}
so that you can pass String, CharBuffer, StringBuilder, StringBuffer and other CharSequence implementations in.
This fact has however nothing to do with java.util.Regex, it only takes benefit of it =)
--------------------------------------------------------------------------------------------------
for more read:-
stackoverflow:-