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

Maximize the Stock profit

Problem Statement
Design algorithms to predicting the maximum profit when you know what the share price of ORANGE FT Group will be for the next N days.

Conditions:
1. You can either buy one share of ORANGE FT Group each day.
2. You can sell any number/no share of shares of Orange owned by you.
What is the maximum profit you can obtain with an optimum trading strategy?

Input
First line: Number of test cases.
Second line: Number of days.
Third line: Share value on particular day.

Output
Maximum profit of each day.

Solution#1: Brute force
  1. Find in maximum value on which share can be sell.
    L
    argest element in the right current element.
  2. If there is any profit to sell the share add it the PROFIT.
  3. Repeat the step#1 and step#2.

Time complexity: O(n^2).
Space complexity: O(1).

Solution#2: Dynamic Programming.
  1. Find out the maximum value of the right side of index and keep update the value in maxArr [] till zero index.
    maxArr[i] = Math.max(maxArr[i+1], values[i]);
  2. To find maximum earn to buy a share:
    p
    rofit = profit + Math.max(maxArr[r]-values[r],0);

Values[]:
10
20
30
40
50

MaxArray[]:
Maximum element from right to left.
50
50
50
50
50

profit = profit + Math.max(maxArr[r]-values[r],0);

Time complexity: O(n).
Space complexity: O(n).

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
     public static void main(String[] args) throws Exception {
           BufferedReader reader = new BufferedReader(
                                 new InputStreamReader(System.in));

           int count = Integer.parseInt(reader.readLine());
           for(int i=0;i<count;i++) {
                int ip_size = Integer.parseInt(reader.readLine());
                int[] values = new int[ip_size];
                String valStr = reader.readLine();
                int j = 0;
                for(String el : valStr.split(" ")) {
                     values[j] = Integer.parseInt(el);
                     j++;
                }

                int[] maxArr = new int[values.length];

                maxArr[values.length-1] = values[values.length-1];
                int q = values.length-2;
                while(q>=0) {
                     maxArr[q] = Math.max(maxArr[q+1],values[q]);
                     q--;
                }
                long profit = 0;
                for(int r=0;r<ip_size;r++) {
                     profit = profit +
                          Math.max(maxArr[r]-values[r],0);
                }
                System.out.println(profit);
           }
     }
}
Input:
1
5
10 20 30 40 50
Output:
100

Reference
Related Posts Plugin for WordPress, Blogger...