// Base class of Exception handling template public abstract class InputStreamProcessingTemplate { public void process(String fileName) throws MyException { InputStream input = null; DataInputStream dis = null; BufferedReader br = null; IOException processException = null; try{ input = new FileInputStream(fileName); dis = new DataInputStream(input); br = new BufferedReader(new InputStreamReader(dis)); doProcess(br); }catch(IOException e) { processException = e; }finally { if(input != null) { try { br.close(); } catch (IOException e) { if(processException != null) { throw new MyException(processException, e,"Error message..." +fileName); }else{ throw new MyException(e, "Error closing InputStream for file " +fileName); } } } if(processException != null) { throw new MyException(processException, "Error closing InputStream for file " +fileName); } } } public abstract void doProcess(BufferedReader input) throws IOException; } // Read file from file system and count no. of words by using Exception handling // template. // public MapgetWordCount(String fileName) throws MyException { final Map myMap = new HashMap (); new InputStreamProcessingTemplate() { @Override public void doProcess(BufferedReader input) throws IOException { String sb = null; while((sb = input.readLine()) != null) { StringTokenizer st = new StringTokenizer(sb, " "); while(st.hasMoreTokens()) { String tmp = st.nextToken().toLowerCase(); if(myMap.containsKey(tmp)) myMap.put(tmp, myMap.get(tmp)+1); else myMap.put(tmp, 1); } } } }.process(fileName); return myMap; } // Sort by frequency of words in HashMap in asc order // public List< Entry > sortByValue(Map myMap) { Set< Entry > set = myMap.entrySet(); List< Entry > list = new ArrayList< Map.Entry >(set); Collections.sort(list, new Comparator< Map.Entry >() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getValue().compareTo(o2.getValue()); } }); return list; }
Wednesday, November 12, 2014
Read file from file system, Count number of words present in this file, and Sort by frequency of words in the file.
Thursday, September 4, 2014
Processes & Threads
Thread:
A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler (typically as part of an operating system).
Scheduler:
The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is a component of a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources. In particular, the threads of a process share the latter's instructions (its code) and its context (the values that its variables reference at any given moment).
A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler (typically as part of an operating system).
Scheduler:
scheduling is the method by which threads, processes or data flows are given access to system resources (e.g. processor time, communications bandwidth). This is usually done to load balance and share system resources effectively or achieve a target quality of service. The need for a scheduling algorithm arises from the requirement for most modern systems to perform multitasking (executing more than one process at a time) and multiplexing (transmit multiple data streams simultaneously across a single physical channel).
The scheduler is concerned mainly with:
- Throughput - The total number of processes that complete their execution per time unit.
- Latency, specifically:
- Turnaround time - total time between submission of a process and its completion.
- Response time - amount of time it takes from when a request was submitted until the first response is produced.
- Fairness - Equal CPU time to each process (or more generally appropriate times according to each process' priority and workload).
- Waiting Time - The time the process remains in the ready queue.
The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is a component of a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources. In particular, the threads of a process share the latter's instructions (its code) and its context (the values that its variables reference at any given moment).
Saturday, June 28, 2014
Wednesday, June 18, 2014
String is immutable or final in Java
1. Requirement of String Pool
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
1.
String string1 =
"abcd"
;
2.
String string2 =
"abcd"
;
If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. Allow String to Cache its Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
3. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
Here is a code example:
1.
boolean
connect(string s){
2.
if
(!isSecure(s)) {
3.
throw
new
SecurityException();
4.
}
5.
//here will cause problem, if s is changed before this by using other references.
6.
causeProblem(s);
7.
}
In summary, the reasons include design, efficiency, and security. Actually, this is also true for many other “why” questions in a Java interview.
1.
String string1 =
"abcd"
;
2.
String string2 =
"abcd"
;
1.
boolean
connect(string s){
2.
if
(!isSecure(s)) {
3.
throw
new
SecurityException();
4.
}
5.
//here will cause problem, if s is changed before this by using other references.
6.
causeProblem(s);
7.
}
Why String is immutable or final in Java
This is one of the most popular String Interview questions in Java, which starts with discussion of, What is String, How String in Java is different than String in C and C++, and then shifted towards what is immutable object in Java , what are the benefits of immutable object , why do you use it and which scenarios do you use it. This is some time also asked as "Why String is final in Java" . Though there could be many possible answer for this question, and only designer of String class can answer this , I think below two does make sense
1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.
In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.
3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.
5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"
Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java". Also to be immutable you have to be final, so that your subclass doesn't break immutability. what do you guys think ?
1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.
In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.
3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.
5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"
Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java". Also to be immutable you have to be final, so that your subclass doesn't break immutability. what do you guys think ?
Few more String related post from Javarevisited, you may like:
Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz34zOyCAI0
Copy Constructor in Java
Shallow Copy
Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.
Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method andoverwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.
Deep Copy
When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.
One more disadvantage with this clone system is that, most of the interface / abstractclass writers in java forget to put a public clone method. For example you can take List. So when you want to clone their implementations you have to ignore the abstract type and use actual implementations like ArrayList by name. This completely removes the advantage and goodness of abstractness.
When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw an exception of type CloneNotSupportedException.
Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.
Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.
Example source code for java clone and shallow copy
class Employee implements Cloneable { private String name; private String designation; public Employee() { this .setDesignation( "Programmer" ); } public String getDesignation() { return designation; } public void setDesignation(String designation) { this .designation = designation; } public String getName() { return name; } public void setName(String name) { this .name = name; } public Object clone() throws CloneNotSupportedException { /* Employee copyObj = new Employee(); copyObj.setDesignation(this.designation); copyObj.setName(this.name); return copyObj; */ return super .clone(); } } public class CloneExample { public static void main(String arg[]){ Employee jwz = new Employee(); jwz.setName( "Jamie Zawinski" ); try { Employee joel = (Employee) jwz.clone(); System.out.println(joel.getName()); System.out.println(joel.getDesignation()); } catch (CloneNotSupportedException cnse) { System.out.println( "Cloneable should be implemented. " + cnse ); } } } |
Output of the above program:
Jamie Zawinski Programmer
//Example:
package com.kony.abc;
public class Galaxy implements Cloneable {
private double fMass;
private final String fName;
/**
* This is the only method which changes the state of a Galaxy
* object. If this method were removed, then a copy constructor
* would not be provided either, since immutable objects do not
* need a copy constructor.
*/
public void setMass( double aMass ){
fMass = aMass;
}
public double getMass() {
return fMass;
}
public String getName() {
return fName;
}
public Galaxy (double aMass, String aName) {
fMass = aMass;
fName = aName;
}
/**
* Copy constructor.
*/
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());
//no defensive copies are created here, since
//there are no mutable object fields (String is immutable)
}
/**
* Alternative style for a copy constructor, using a static newInstance
* method.
*/
public static Galaxy newInstance(Galaxy aGalaxy) {
return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());
}
/**
* Test harness.
* @throws CloneNotSupportedException
*/
public static void main (String args[]) throws CloneNotSupportedException{
Galaxy m101 = new Galaxy(15.0, "M101");
Galaxy m101CopyOne = new Galaxy(m101);
Galaxy cloneobj = (Galaxy) m101.clone();
System.out.println(cloneobj.getMass());
m101.setMass(40.0);
m101CopyOne.setMass(25.0);
System.out.println("M101 mass: " + m101.getMass());
System.out.println("M101Copy mass: " + m101CopyOne.getMass());
Galaxy m101CopyTwo = Galaxy.newInstance(m101);
m101CopyTwo.setMass(35.0);
System.out.println("M101 mass: " + m101.getMass());
System.out.println("M101CopyTwo mass: " + m101CopyTwo.getMass());
System.out.println(cloneobj.getMass());
}
}
References:
|
Subscribe to:
Posts (Atom)