Tuesday, 22 December 2015

Naïve String Matching Algorithm

Naïve String Matching Algorithm

It employs a Brute Force technique to identify the presence of a pattern in the given text.

It is not efficient algorithm because it takes the time complexity of the algorithm to check for a sub string is O((m-n)n) where m is the length of the text and n is the length of the pattern (sub string) to be searched.

There is no preprocessing is required for this algorithm unlike KMP algorithm.

Preprocessing time: 0 (no preprocessing)
Matching time: O((n-m)m).

NaiveStringMatcher(text, pattern)
tLen ← length [text]
pLen ← length [pattern]

for i ← 0 to tLen - pLen do
     mCount = 0;
for j ← 0 to pLen do
    if text[i] != pattern[j+i]
        break;
    mCount++;
     if(mCount == pLen)
           return Valid match found at position : + i!!



public class NaiveStringMatch {
      public static void main(String[] args) {
            String text = "I love to work on the algorithms!";
            String pattern = "the algorithms";
            naiveStringMatcher(text, pattern);
      }

      /**
       * Implementation of Naive String matching algorithm.
       * @param text
       * @param pattern
       */
      private static void naiveStringMatcher(String text, String pattern) {

            char[] txtArr = text.toCharArray();
            char[] patArr = pattern.toCharArray();

            int tLen = txtArr.length;
            int pLen = patArr.length;

            for (int i = 0; i < tLen - pLen; i++) {

               int charMatchCount = 0;
               for (int j = 0; j < pLen; j++) {

                    /**
                     * If pattern mismatch, break next searching point.
                     **/
                     if (patArr[j] != txtArr[i + j]) {
                          break;
                     }
                     charMatchCount++;

               }
               if (charMatchCount == pLen) {
                     print("String found at "+(i+1)+" position!!");
                     break;
               }
            }
      }

      private static void print(String string) {
            System.out.println(string);
      }
}
Output:
String found at 19 position!!

Sunday, 13 December 2015

Generate serialVersionUID using Java Program

serialVersionUID can be generated by using getSerialVersionUID() method of the ObjectStreamClass class.

SerialiazedClass.java
package com.serial;
import java.io.Serializable;

class SerialiazedClass implements Serializable {
     String name;
     public void setName(String name) {
           this.name = name;
     }
}

GenerateSerialVerUID.java

import java.io.ObjectStreamClass;
public class GenerateSerialVerUID {
    
     public static void main(String[] args) {
          
           Class hashClass = SerialiazedClass.class;
          
           ObjectStreamClass osc = ObjectStreamClass.lookup(hashClass);
           long serialID = osc.getSerialVersionUID();

           System.out.println(serialID);
     }
}
Output:
1623809446810541828

Saturday, 12 December 2015

How to generate serialVersionUID in Java?

Generate serialVersionUID of Employee class

import java.io.Serializable;
public class Employee implements Serializable {
     private String name;
     public Employee(String name) {
           this.name = name;
     }
     public String getName() {
           return name;
     }
}

1. serialver command
JDK has a build in command called “serialver” to generate the serialVersionUID automatically.


C:\Users\awadh\Desktop>javac Employee.java
C:\Users\awadh\Desktop>serialver Employee
Employee:  private static final long serialVersionUID = -6607742892470200720L;




2. serialver tool


Run command: serialver –show
C:\Users\awadh\Desktop>serialver -show
Put the class description in the tool and click on the show button.
private static final long serialVersionUID = -6607742892470200720L;



3. Using Eclipse IDE

Friday, 11 December 2015

Why SerialVersionUID is static?


The serialization runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that is compatible with respect to serialization.

If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.

The serialVersionUID determines compatibility between different versions of a class. Since the property is bound to the class, it has to be made static.


static variables are not serialized with the object.

However, serialVersionUID is a must in serialization process.


When an object is serialized, the serialVersionUID is serialized along with the other contents. This is one exception to the general serialization rule that, “static fields are not serialized”.

References:
http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html#4100

Need externalizable when we already have serializable

When you serialize any object using serializable, apart from fields, all objects that belong to object map and that can be reached using instance variable will also be serialized.

For example:
  • If you have Employee class and its superclass is the person then it will serialize all superclass objects (such as the person) until it reaches "Object" class.
  • Similarly, if Employee has an instance variable of address class then it will serialize whole object map of address also.

Do you really want this much overhead when all you want to serialize is empId and empName.


JVM uses reflection when you use serializable which is quite slow.

While serializing, information about class description which includes the description of its superclass and instance variable associated with that class also get stored in the stream. Again this is also a performance issue.

Thursday, 10 December 2015

What is the problem if I synchronized only setters to make an object Thread-safe?

Scenario

Make setters synchronized only

public class ThreadSafeObject {
    private int value;

    public int getValue() {
        return value;
    }
    public synchronized void setValue(int value) {
        this.value = value;
    }
}

Changes to the object may not be visible to any reading thread, because JVM will not ensure that the reading thread's memory (like, cache) is in sync with the writing thread.

So, reader thread may still get out-of-date (older) values from its thread's cache than new value set by writing thread.

Solution

1.Make getters and setters both synchronized: No dirty read

When getters are synchronized, there will be lock on the object which will not allow other threads to modify the object state.
And synchronized also help to read the object from Main memory (not from cache) i.e NO DIRTY READ.

2.Use volatile keyword to ensure that the value has been read from Main memory.

Tuesday, 8 December 2015

Java Runtime class


public class Runtime extends Object

The java.lang.Runtime class allows the application to interface with the environment in which the application is running.

It helps to us interact with java run-time environment. This class contains method to invoke Garbage Collector, free memory, total memory available or execute a process etc.

java.lang.Runtime class is a Singleton for a java application.

Some useful methods:
Method
Description
public static Runtime getRuntime()

Runtime is Singleton class.
This method returns the instance of Runtime class.

public void exit(int status)

This method terminates the currently running Java virtual machine by initiating its shutdown sequence.

public void addShutdownHook(Thread hook)

Registers new hook thread.
public Process exec(String command)throws IOException

Executes given command in a separate process.

public int availableProcessors()

Returns the number of available processors.

public long freeMemory()

Returns amount of free memory in JVM.

public long totalMemory()

Returns amount of total memory in JVM.

boolean removeShutdownHook(Thread hook)

This method de-registers a previously-registered virtual-machine shutdown hook.



Open Command prompt using exec() method
import java.io.IOException;
public class Test {
     public static void main(String[] args) throws Exception {
           Runtime rt = Runtime.getRuntime();
           try {
                rt.exec(new String[]{"cmd.exe","/c","start"});

           } catch (IOException e) {
           }
     }
}

Memory test using Runtime class:

public class Test {
     public static void main(String args[]) { 
           Runtime runtime = Runtime.getRuntime(); 
           System.out.println("Total Memory:"+runtime.totalMemory()); 
           System.out.println("Free Memory: "+runtime.freeMemory()); 

           for(int i=0;i<Integer.MAX_VALUE;i++){ 
                Object object = new Object(); 
           }
          
           System.out.println("After creating instance of Object");
           System.out.println("Free Memory: "+runtime.freeMemory());
          
           System.out.println("After calling gc()");
           System.gc();
           System.out.println("Free Memory: "+runtime.freeMemory()); 
     } 
}

Output:
Total Memory:61800448
Free Memory: 61476688
After creating instance of Object
Free Memory: 60996792
After calling gc()
Free Memory: 61335224
Related Posts Plugin for WordPress, Blogger...