Thursday, 29 December 2016

How to Know Free Disk Space

Disk Filesystem(df) command can be used to know free space.

Default Usage: df -h



Happy Learning Day 2 :)


Wednesday, 28 December 2016

How to Find Directory or File Size - Disk Usage

1) Disk Usage(DU) command can be used to know sizes of directories,sub-directories and files.
2) This command works in recursive manner.

Default usage: du -h directory.
   i)   Here h option is for displaying sizes in human readable format.
   ii)  Last line displays, total size of directory.
   iii) This command only considers sub directories by default.


3) Option -a can be used to include files in the directory.
   
 
4) Option -s can be used to know size of directory.

    'S' stands for summary

5) --time can be used for sorting based on modification date.
6) --exclude="*.xml" can be used for excluding specific type of files while computing size of directory.

Happy Learning 😊

Thursday, 2 April 2015

Implementing Shutdown Hook in Java

Graceful shutdown of application is very important aspect to leave our application in consistent state. The primary task of shut downing application is releasing all resources back to system.

We will learn how to bring down, Spring and normal Java apps.

You would have noticed invoking registerShutdownHook() on AbstractApplicationContext in Spring apps, so that Spring gets a chance to clean up it's resources before JVM goes down.

try
{
   AbstractApplicationContext context= new ClasspathXmlApplicationContext("application-config.xml")
   context.registerShutdownHook();
}
finally
{
   context.close();
}

Pls remember, there is no guarantee that always shutdown hook gets executed. for example, if user uses Kill -9 etc hook won't gets it's turn. in cases of, Kill/ctl+c System.exit(0), hook runs before JVM goes off.

This way Spring will cleanup container and invoke destroy methods on beans.

It's also good practice to call close() in finally block. This is because if our application thows unhandled runtime exception, we might of background threads,started by some beans still running and JVM will not terminate.

In case of normal applications, we can register hook with JVM by calling addShutdownHook(Runnable) on Runtime instance.

For example,

public class ShutdownHookExample
{

public static void main(String[] args)
{
ShutdownHookExample shutdownHook = new ShutdownHookExample();
shutdownHook.registerShutDownHook();
}
private Thread shutDownHook = new Thread()
{
  public void run()
  {
  cleanUp();
  }
};

private void registerShutDownHook()
{
//Registering hook with VM
Runtime.getRuntime().addShutdownHook(this.shutDownHook);
while(true);
}

private void cleanUp()
{
System.out.println("cleaning resources");
}
}

Compile an run above program from command prompt and press ctl+c to bring down program and we could see cleaning resources printing in console.

We can close DB connections,File handlers etc in cleanUp method.

Hope you find this post useful.

Happy Learning.




Tuesday, 24 March 2015

The magic of XOR

XOR is an interesting operation and stands for 'exclusive OR'.  In this post, I will cover few problems which can be solved by using XOR.

Truth Table:

P ^ Q == (~P & Q) | (P & ~Q)

Problem 1:  Find number occurring odd no.of times

We can solve this problem by exploiting below mentioned XOR property.

p1^p2^p3^...^pn = true if no. of variables with the value true is ODD
p1^p2^p3^...^pn = false if no. of variables with the value true is EVEN
(This property doesn't hold true for variables with false value)


Problem 2: Find missing number in a range with out duplicates

1) Find XOR value of all numbers in the range
2) Find XOR value of all numbers in the array
3) XOR above values to know missing number

Problem 3: Swapping two numbers with out taking help of temp variable

Let's say we have to swap values of X and Y.

// X = A ,Y = B
// X = A ^ B, Y=B
X =  X ^ Y 

//Y = A^B ^ B -> A
Y =  X ^ Y

//A^B^A -> B
X = X ^ Y

X = B,Y=A

More about XOR on 

Hope you find this post useful.

Happy Learning



Monday, 23 March 2015

Given array and a number x, check for pair in arr with sum x


We can directly jump to brute force approach and end up with o(n2) complexity solution.










No. comparisons = ( n(n+1) / 2 ) - n where n is array length.

Problem with above approach are
a. Trying unnecessary combinations
    means more comparisons,add operations,time consumption etc
b. Giving interviewer one chance to reject us :)

Better approach 1:

Whenever we are dealing with arrays, following things, we need to keep in mind

1) Array sorting.
2) Input range.
3) minimum no.of comparisons/copy operations needed.
4) Usage of index pointers
5) Boundary conditions (<arr.length , >-1)

Most of the times, sorting and binary search combination solves most of the array problems for us.


Best thing about this approach is, we are avoiding unnecessary combinations by taking advantage of sorted data.

If we find, summation is less than X, then we should try adding next big number from beginning otherwise try adding next small number from ending.

This solution works in o(nlogn) sorting + o(n) time which is way better than o(n2).

Best apporach 2:

If there is no constraint on extra space, then we can try out below approach.

Note1: We should know range of input
Note2: This solution works for negative numbers as well !



Above approach does the trick in o(n) complexity with additional space.

Above approach works like a charm, while dealing with negative numbers. All we have to do is try converting all -ve numbers into positive ones.

     int[] arr = new int[]{1,4,45,-6,10,-8};
     int x = 2

Steps:
a) Find least minimum number and it's absolute value: |-8| = 8
b) Add 8 to all input values: {9,12,53,2,18,0}
c) Add 8 + 8 to x: 16 +2 = 8

10 + (-8) = 2
(10 + 8) + -8 = 10;
18+ -8+8 = 10+8
18 = 18

Hope you find this post useful.

Happy learning :)






Tuesday, 2 April 2013

Tricky interview question on Volatile keyword in Java

As we all know that, 
1) Volatile prevents the threads from caching variable values locally.
2)  It plays key role in inter thread communications.

But there is a tricky question on volatile i.e 'Is there any side affects on non volatile variables if we use volatile '. Have a look at the below program to know the answer.

public class TestVolatile implements Runnable
{
int num1 = 10;
int num2 = 30;
 volatile int sum;
 
public void run() 
{
           // First thread performs write operations on sum and num1
          // Second thread performs read operations to get latest values from main memory and                        //then perform write
sum = num1 + num2;
num1 = 300;
   System.out.println(Thread.currentThread().getName()+" - "+sum);
    System.out.println(Thread.currentThread().getName()+" - "+num1);
   System.out.println(Thread.currentThread().getName()+" - "+num2);
}
public static void main(String args[])
{
TestVolatile TestVolatile =  new TestVolatile();
Thread thread1 = new Thread(TestVolatile);
Thread thread2 = new Thread(TestVolatile);
thread1.setName("Thread1");
thread2.setName("Thread2");
thread1.start();
thread2.start();
}
}

You would have noticed that, num1 value of one thread is effecting sum computation of another thread . Does this mean that using volatile also has side-effects to the usage of non-volatile variables? YES.

Reason: Any writes in the thread that wrote to the volatile before doing so will be seen by the thread reading the volatile after having done so

Refer below links for more info: