Sunday, 9 June 2013

Interview Question #13 synchronization on static function/method.

Let me clarify the question with an example. You have the following class.

public class Counter{
private static int count = 0;

public static synchronized int getCount()
{
  return count;
}

public synchronized setCount(int count)
{
   this.count = count;
}

}


You have multi threaded environment. Can two threads simultaneously access
or process getCount() and setCount() methods? 
Even if we have following case.

Counter myCounter = new Counter();
myCounter.setCount(10);
myCounter.getCount();
 
 
 

Answer

First of all you should not access static functions/block using class instance. Though it is perfectly valid to do so. Why is it valid? Each of the class instances(objects) have class information and hence can hence access it. Lets get to our original question on synchronization.

Answer is yes! Two threads can simultaneously operate/process on the two functions getCount() and setCount(). This is because when synchronized method setCount() is called thread acquires an object level lock where as when getCount() method is called it being a static method(owned by class rather than it's instances) acquires a class level lock.

When you use synchronized method or a block lock is obtained on the monitor if the corresponding instance. So in above example for setCount() method lock obtained will be on the myCounter instance where as for method getCount() which is a static or class method lock is obtained on the Class object. You can get this object by using .class keyword or getClass() method. This Class object will be same for all the instances of that class.

Saturday, 1 June 2013

How to count number of files in a linux directory?

Sometime you copy a lot of files from a directory or another media to some other directory and you wish to know how many files are copied. Here is how you can get to know how many files you have in your directory.

  1. Navigate to the directory you wish to count files from.
  2. Type in the following command ls -1 | wc -l
  3. You must get the file count as the output

 

 ls command

   ls command is used to list contents of the directory.  You can see the manual of the command by typing man ls in your terminal. Frequently used options with ls command are
  • -a, --all
                  do not ignore entries starting with .
  • -d, --directory
                  list directory entries instead of contents, and do not dereference symbolic links 
  • -l     use a long listing format
  • -1     list one file per line

 wc command

wc command is used for word count.
You can see the manual of the command by typing man wc in your terminal. Frequently used options with ls command are
  • -l, --lines
                  print the newline counts
  • -w, --words
                  print the word count

 Understanding ls -1 | wc -l

 We have used ls -1 in the command to find number of files in a directory. This will return the directory contents listed one file per line. This we pipe it to wc -l command which will print the newline counts. 

Note : If you use ls -l instead of ls  -1 as in ls -l | wc -l instead of ls -1 | wc -l. You will get count 1 more than the the actual number of files as this will also print one more line like 
total 116
drwxr-xr-x 3 aniket aniket  4096 May 31 22:08 Desktop
drwxr-xr-x 2 aniket aniket  4096 May  1 20:25 Downloads

...

Total line tells you  the total size of your directory in blocks (1024 bytes) on the hard disk, which is 116 in our example.

Screen shot:



he above method will count symbolic links as well as subdirectories in targetdir (but not recursively into subdirectories).

Excluding subdirectories


If you want to exclude subdirectories, you can do.
find yourDir -type f  -maxdepth 1 | wc -l


-type f ensures that the find command only returns regular files for counting (no subdirectories).

By default, the find command traverses into subdirectories for searching. -maxdepth 1 prevents find from traversing into subdirectories. If you do want to count files in the subdirectories, just remove -maxdepth 1 from the command line.

Note that the find command does NOT classify a symbolic link as a regular file. Therefore, the above find -type f command does not return symbolic links. As a result, the final count excludes all symbolic links.

To include symbolic links, add the -follow option to find.
 
find targetdir -type f -follow  -maxdepth 1 | wc -l 
 

Friday, 24 May 2013

Can Instance variables be overridden by inheritance in Java?

We know that functions can be overridden by inheritance but are instance variables overridden?
Go through the following code

We have a class called  Superclass which has an instance variable name and an public method printName() to print it.

public class Superclass {
    private String name = "John";
   
    public void printName()
    {
        System.out.println("Name is " + name);
    }
}


Now we write Subclass which extends Superclass. This class also has an instance variable called name and a function with same name(overridden).

public class Subclass extends Superclass {
   
    private String name = "Sam";
   
    public void printName()
    {
        System.out.println("Name is " + name);
    }

}
 

Finally we do the following

Superclass myClass = new Subclass();
        myClass.printName();


and guess what the output is? Even before that is it correct to have variables with same name is super class and subclass.

The answer is Yes!!
The output is : Name is Sam

Explanation

  Simple explanation is only functions are overridden not the variables. When we call  printName() function on myClass object it first check whether the reference type SuperClass has this function. if it is not there Java will throw an exception. Since it is present we can proceed. Now java will find what kind of object this actually is. It will travel down the inheritance tree and call the appropriate function of  Subclass. Since name is Sam in SubClass it is printed.

Sunday, 19 May 2013

Accesing private variables using Reflection API

Reflection API in Java comes very handy to test class variables and methods at runtime. You can call it a type of hack as it violates the principle of Data Encapsulation. Let us see a code that demonstrates how can we access private variables using Reflection API and even edit it.

Code :


public class Someclass {
    private String name = "John";

}

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String args[]) throws Exception
    {
       
Someclass myClass = new Someclass();
        Field fs = myClass.getClass().getDeclaredField("name");
        fs.setAccessible(true);
        System.out.println("Variable is " + fs.getName() + " and value is " + fs.get(myClass));
        fs.set(myClass, "Sam");
        System.out.println("Variable is " + fs.getName() + " and value is " + fs.get(myClass));
    }
}

Output :  



Explanation : 

          Note that the private variable name is in the Someclass class and our main method is in the Test class. According to OOP principles we should not be able to access the private variable name. Using the instance of the class myClass we get the declared field with name name. Then we set it accessible property to true. Then we can access it and print it(as shown in the output). Moreover we can also change it's value using Reflection API. fs.set(myClass, "Sam") method does that.

For more details you can refer to it's documentation.
  

Saturday, 18 May 2013

Hashtable example in Java.

In last post we saw difference between a HashMap and a Hashtable. Let us now see what Hashtable is and how do we use it.

If you see the source code implementation of Hashtable it is similar to that of map. Infact Hashtable implements Map interface.As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. For more information refer to Hashtable JavaDocs.

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable
{...

Lets see how can we use Hashtable.

Code : 

package testCodes;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    
    public static void main(String args[])
    {
        Hashtable<String, String> hashTable = new Hashtable<String, String>();
        //Populating Hashtable
        hashTable.put("Name", "John");
        hashTable.put("Country", "USA");
        hashTable.put("Gender", "Male");
        //Printing whole table
        System.out.println("hashTable : " + hashTable);
        //printing individual values
        Enumeration<String> data = hashTable.keys();
        while(data.hasMoreElements())
        {
            String str = (String) data.nextElement();
            System.out.println(str + " : " + hashTable.get(str));
        }
    }    
}

Output :


Understanding the code : 

     Code is very much similar to HashMap usage but has slight variations. Note Hashtable is a class and not an Interface. put() and get() method remain the same as that of HashMap. What is different is the concept of Enumeration. As specified earlier when Hashtable was introduced there was no Collections and hence no iterators. What we had to use was Enumeration. Enumeration is similar to Iterator. We check whether it has more elements using hasMoreElements() function, if yes access the next element using nextElement() function. Note the use of generics remain the same.

Few very common differences between a HashMap and a Hashtable are -
  • Hashtable is synchronized where as HashMap is not.
  • Hashtable does not allow null keys or values whereas HashMap allows one null key and any number of null values.
  • keys() method of Hashtable return Enumeration where as keySet() method of HashTable returns a Set which can be iterated over as it implements Iterable interface - Enumeration does not.

 Related Links

t> UA-39527780-1 back to top