Tuesday, 26 February 2013

Sample Socket Connection Example

Telnet Server Implementation Code:

class TelnetServer {
   private final ServerSocket serverSocket = new ServerSocket(4444);

   public void start(){
      try {
            log.info("Starting server on port " + serverSocket.getLocalPort());
            System.out.println("Starting server on port " + serverSocket.getLocalPort());
            while (isRunning && serverSocket != null) {
                log.info("Waiting for client connection!");
                System.out.println("Waiting for client connection!");
                Socket socket = serverSocket.accept();
                log.info("Creating new telnet client connection");
                System.out.println("Creating new client connection");
                connManager.createConnection(socket);// Create a thread to handle socket 
            }
        }
   }

}



ConnectionHandler Implementation Code:

class ConnectionHandler implements Runnable{


private final Socket socket;

public ClientConnection(){
          socket = new Socket("localhost", 4444);
}

@Override
public void run()

 try {
            iStream = new DataInputStream(socket.getInputStream());
            oStream = new DataOutputStream(socket.getOutputStream());
            out = new PrintWriter(socket.getOutputStream(), true);

            cmdContext = CommandContext.createInstance(new File("."),                               
            socket.getLocalAddress().getHostName(), socket.getInetAddress().toString());
            cmdExecutor = new CommandExecutor();
            System.out.println(cmdContext);

            while ((line = iStream.readUTF()) != null && !line.equals(".")) {
                input = input + line;
                System.out.println("Command Received: " + line);
                out.print(input);
                oStream.writeUTF(getCommandResponse(cmdContext, cmdExecutor, line));
             }
         }

    }
}

*********************************************************

TelnetClient implementation :


public class TelnetClient {
    public static void main(String args[]) throws Exception {
        Socket soc = new Socket("localhost", 4444);
        String Command;
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Welcome to Telnet Client");
        System.out.println("< Telnet Prompt >");
        while ((Command = br.readLine()) != null && !Command.equals(".")) {
            dout.writeUTF(Command);//sends command to server
            System.out.println(din.readUTF()); //gets the response of server
        }
        soc.close();
        din.close();
        dout.close();
        br.close();
    }
}

Monday, 11 February 2013

Serialize Array in Java


For Serializing Array we can use ObjectOutputStream/ObjectInputStream classes.

NOTE: An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.


public class SerializeArray {
    public static void main(String[] args) {

        String[][] twoD = new String[][]{new String[]{"Alex", "Hyde"},
                new String[]{"Rohan", "Disuza"}};

        String[][] newTwoD = null; // will deserialize to this

        System.out.println("Before serialization");
        for (String[] arr : twoD) {
            for (String val : arr) {
                System.out.println(val);
            }
        }

        try {
            FileOutputStream fos = new FileOutputStream("test.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(twoD);

            FileInputStream fis = new FileInputStream("test.dat");
            ObjectInputStream iis = new ObjectInputStream(fis);
            newTwoD = (String[][]) iis.readObject();

        } catch (Exception e) {

        }

        System.out.println("After serialization");
        for (String[] arr : newTwoD) {
            for (String val : arr) {
                System.out.println(val);
            }
        }
    }
}


Tuesday, 15 January 2013

When finally block is NOT called?


Finally block is NOT called in following conditions
  • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.
  • if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
  • If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.
  • If there is infinite loop, or deadlock then also finally block will not get executed

Is Java Pass by Reference or Pass by Value?

Java always pass by value. It confuses when we pass an object reference in method call and method implementation changes objects attributes. When we see these changes after returning from method call it feels like java use pass by reference but its not true. Java uses pass by value and mthod try to change value it will not reflect after call. Changing value means re-initianciation . The first case is referenced values got mutated but it was still pass by value.


It goes like this:
public void foo(User user) {
  user.name.equals("Mayank"); // true
  user = new User("Mike");
  d.name.equals("Mike"); // true
}

User user1 = new User("Mayank");
foo(user1);
user1.name.equals("Mayank"); // still true
In this example user1.name will still be "Mayank". "user" is not overwritten in the function as the object reference is passed by value.
Likewise:
public void foo(USer user) {
  user.name.equals("Mayank"); // true
  user.setname("Mike");
}

User user1 = new Use("Mayank");
foo(user1);
user1.name.equals("Mayank"); // Not true anymore as name got mutated 
user1.name.equals("Mike"); // true

For further details please see this link
http://stackoverflow.com/questions/40480/is-java-pass-by-reference

String vs StringBuffer vs StringBuilder


The main difference between the three most commonly used String classes as follows.
  • StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable.
  • StringBuffer class implementation is synchronized while StringBuilder class is not synchronized. 
Note: If you keep forgetting which one is synchronized which one is not remember StringBuilder is just implmentation of builder pattern so the other is Synchronized which is StringBuffer
  • Concatenation operator "+" is internally implemented by Java using StringBuilder.
Note: For more details see this link

Criteria to choose among String, StringBuffer and StringBuilder
  • If the Object value will not change in a scenario use String Class because a String object is immutable.
  • If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
  • If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

Mutable or Immutable

What are immutable classes?

Immutable classes are the one whose objects visible attributes can not be changed once instantiated.

How to make class immutable?

To make a class immutable adhere followings :
1. Make class final
2. Make all fields final
3. Class should not have any Mutator method ( setter methods)
4. Don't leek any references of class attributes. (For getter of references create new object i.e. deep cloning, return new instance of referenced object.

What are the benefits of immutable?

1. Can be used as Cache:  

As immutable objects don't change their state or values its safest cache that can be used across without any danger of corruption.

2. Thread safety by Immutability:

Immutable objects are inherently thread safe and can be shared across multiple threads safely.

3. Can be used for implementing Flyweight Design Pattern:

The Flyweight pattern employs a factory method to dispense references to immutable fine-grained objects and uses sharing to keep the object count down by only having a single instance of the object instead of keep creating instance of these objects through out application. For example String. 

4. Good keys for hashing:

Immutable objects are best way to define keys for any hashing data structure. They are memory leek free otherwise due to mutation keys can make associated values not reachable and cause memory leek. In fact we should always use immutable keys.

For example, consider a Person bean with an value-based equals method:
Map<Person, String> map = ...
Person p = new Person();
map.put(p, "Hey, there!");
p.setName("Daniel");
map.get(p); // => null

The Person instance gets "lost" in the map when used as a key because it's hashCode and equality were based upon mutable values. Those values changed outside the map and all of the hashing became obsolete. 


Why Immutable class needs to be final?

For safety and security it is good practice to make class final when it is suppose to be immutable. It's not mandatory but avoids any hack or programming errors. Otherwise in extended sub classes or using anonymous class instances you can override getters and simulate mutability by returning changed values.
For example:
ImmutableClass object = new ImmutableClass(x, y){
     @Override
     public String getX(){
     return "Hello";
   }
}

Example of Immutable class:

class User implements Cloneable
{
    private String userName;
    private int userNode;

    User(String name, int node)
    {
        userName = name;
        userNode = node;
    }

    public String userName()
    {
        return userName;
    }

    public int getUserNode() {
        return userNode;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public User deepClone() {
        return new User(this.userName(), this.getUserNode());
    }

    @Override
    public String toString() {
        return String.format("User{userName='%s', userNode=%d}", userName, userNode);
    }
}

final class DiskDriveInfo implements Cloneable
{
    private final int driveSize;
    private final String volumeLabel;
    private final User driveShare;

    DiskDriveInfo(int size, String volLabel, User share)
    {
        driveSize = size;
        volumeLabel = volLabel;
        driveShare = share;
    }
    public int size()
    {
        return driveSize;
    }
    public String label()
    {
        return volumeLabel;
    }

    public User getUser() {
        // Dont use default clone method as it just creates a new reference to the same object so you will leek        reference here.
        //return (User) driveShare.clone();
        return driveShare.deepClone();

    }

    // This is just to show that you can write clone method but for immutable objects it has no use.
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return String.format("DiskDriveInfo{driveSize=%d, volumeLabel='%s', driveShare=%s}", driveSize, volumeLabel, driveShare);
    }
}



Sunday, 12 August 2012

Atomic Classes in Java

From Java 5 onwards Java has added multiple thread safe atomic classes in 'java.util.concurrent' package which can be categories in followings:
1. Atomic class for atomic access to primitive types
  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
  • AtomicReference
2. Atomic access to different arrays:
  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicReferenceArray
3. Atomic Field Updaters:  These classes are used to wrap up atomic access, via reflection, to volatile fields of another class.
  • AtomicIntegerFieldUpdater
  • AtomicLongFieldUpdater 
  • AtomicReferenceFieldUpdater 
4.  Atomically integrate a boolean or integer with a reference field:
  • AtomicMarkableReference 
  • AtomicStampedReference