Tuesday, August 23, 2011

Read later


When using a factory your code is still actually responsible for creating objects, by DI you outsource that responsibility to a framework which is separate from your code.

 Dependency Injection is more of a architectural pattern for loosely coupling software components. Factory pattern is just one way to separate the responsibility of creating objects of other classes to another entity. Factory pattern can be called as a tool to implement DI. Dependency injection can be implemented in many ways like DI using constructors, using mapping xml files etc.

Factory Method

http://www.blackwasp.co.uk/FactoryMethod_2.aspx

Servlet life cycle
creates a single instance of each servlet and creates multiple threads to handle the service() method.



Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?

Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID

2) Now call Collections.sort() method and pass list as an argument.

Now consider that Employee class is a jar file.

1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .

2) Call Collections.sort() on the list and pass comparator as an argument.

 Hibernate caching overview

Hibernate has several levels and kinds of cache. There is a first level cache of Hibernate entities stored in and scoped specifically to a particular open Session. In Hibernate, entity objects are never shared between sessions.
There is also a second level cache that is shared across sessions. The second level cache is divided into regions of four types: entity, collection, query, and timestamp. Entity and collection regions cache the data from entities and relationships (but not the entities themselves). The query and timestamp caches are related and the subject of our focus here.
The query cache is used to store the result set of a query made against the database. The key of the query cache contains the query string itself and any bind parameters passed with the query. The value consists not of the entity field values but just the primary key identifiers for all of the entities returned by the query. When a query is made that hits the query cache, that set of entity identifiers can be retrieved and then resolved through the first or second level caches instead of retrieving those entities from the database.
The timestamp cache keeps track of the last update timestamp for each table (this timestamp is updated for any table modification). If query caching is on, there is exactly one timestamp cache and it is utilized by all query cache instances. Any time the query cache is checked for a query, the timestamp cache is checked for all tables in the query. If the timestamp of the last update on a table is greater than the time the query results were cached, then the entry is removed and the lookup is a miss.


 The hibernate cache does not store instances of an entity - instead Hibernate uses something called dehydrated state. A dehydrated state can be thought of as a deserialized entity where the dehydrated state is like an array of strings, integers etc and the id of the entity is the pointer to the dehydrated entity. Conceptually you can think of it as a Map which contains the id as key and an array as value. Or something like below for a cache region:

{ id -> { atribute1, attribute2, attribute3 } }
{ 1 -> { "a name", 20, null } }
{ 2 -> { "another name", 30, 4 } }

If the entity holds a collection of other entities then the other entity also needs to be cached. In this case it could look something like:

{ id -> { atribute1, attribute2, attribute3, Set{item1..n} } }
{ 1 -> { "a name", 20, null , {1,2,5} } }
{ 2 -> { "another name", 30, 4 {4,8}} }

The actual implementation of the 2nd level cache is not done by Hibernate (there is a simple Hashtable cache available, not aimed for production though). Hibernate instead has a plugin concept for caching providers which is used by e.g. EHCache.

Sunday, August 21, 2011

Interview Question - New features of JDK 1.5


  • Generics
  • Annotations
  • Enumerations
  • Swing - New skinable look and feel
  • Enhanced for loop
  • Java Util Concurrent.

Monday, August 1, 2011

My favorite Java Concurrency interview questions with answers?

1. What is deadlock in Java? How to detect it and prevent it?

Ans : Multiple threads waiting forever due to cyclic locking dependency.

Thread T1  holds lock L1 and tries to acquire lock L2 BUT at the same time

Thread T2 holds L2 and tries to acquire L1. Both threads will wait forever.

Types of deadlocks
  •   Lock ordering deadlocks : 
  •   Nested Lock acquisitions
  •   Resource deadlock

Avoiding Deadlocks
  1. lock ordering : http://jaroslav-sedlacek.blogspot.com/2011/03/deadlock-despite-consistent-lock.html
  2. timed tryLock feature of explicit Lock classes.
  3. use thread dump for analysis.

Synchronized methods (in Java):


Another favorite question of interviewers is, "What is a synchronized method in
Java?" Each object in Java has its own mutex. Whenever a synchronized method is
called, the mutex is locked. When the method is finished, the mutex is unlocked.
This ensures that only one synchronized method is called at a time on a given object.


Deadlock:


Deadlock is a problem that sometimes arises in parallel programming. It is typified
by the following, which is supposedly a law that came before the Kansas legislature:
"When two trains approach each other at a crossing, both shall come to a full stop
and neither shall start up again until the other has gone."
Strange as this sounds, a similar situation can occur when using mutexes. Say we
have two threads running the following code:




Thread 1:
acquire(lock1);
acquire(lock2);
[do stuff]
release(lock1);
release(lock2);
Thread 2:
acquire(lock2);
acquire(lock1);
[do stuff]
release(lock2);


release(lock1);


Suppose that thread 1 is executed to just after the first statement. Then, the
processor switches to thread 2 and executes both statements. Then, the processor
switches back to thread 1 and executes the second statement. In this situation,
thread 1 will be waiting for thread 2 to release lock1, and thread 2 will be waiting
for thread 1 to release lock2. Both threads will be stuck indefinitely. This is called
deadlock.




How can we ensure that deadlock does not occur?


Answer: There are many possible answers to this problem, but the answer the
interviewer will be looking for is this: we can prevent deadlock if we assign an order
to our locks and require that locks always be acquired in order. For example, if a
thread needs to acquire locks 1, 5, and 2, it must acquire lock 1, followed by lock 2,
followed by lock 5. That way we prevent one thread trying to acquire lock 1 then
lock 2, and another thread trying to acquire lock 2 then lock 1, which could cause
deadlock. (Note that this approach is not used very often in practice.)






What is polymorphism?


Interviewers love to ask people this question point‐blank, and there are several
possible answers. For a full discussion of all the types of polymorphism, we
recommend looking at its Wikipedia page. However, we believe that a good answer
to this question is that polymorphism is the ability of one method to have different
behavior depending on the type of object it is being called on or the type of object
being passed as a parameter. For example, if we defined our own "MyInteger" class
and wanted to define an "add" method for it (to add that integer with another
number), we would want the following code to work:
MyInteger int1 = new MyInteger(5);
MyInteger int2 = new MyInteger(7);
MyFloat float1 = new MyFloat(3.14);
MyDouble doub1 = new MyDouble(2.71);
print(int1.add(int2));
print(int1.add(float1));
print(int1.add(doub1));
In this example, calling "add" will result in different behavior depending on the type
of the input.







Thursday, April 21, 2011

How HashMAp works in Java

From http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html


How HashMAp works in Java
HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list.
Also hashMap stores both key+value tuple in every node of linked list.

Wednesday, April 6, 2011

index data structure

What types of index data structures can you have? 
An index helps to faster search values in tables. 
The three most commonly used index-types are: 
- B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value. Needs a lot of space and is the default index type for most databases. 
- Bitmap: string of bits for each possible value of the column. Each bit string has one bit for each row. Needs only few space and is very fast.(however, domain of value cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD) 
- Hash: A hashing algorithm is used to assign a set of characters to represent a text string such as a composite of keys or partial keys, and compresses the underlying data. Takes longer to build and is supported by relatively few databases.

Tuesday, April 5, 2011

Java programming dynamics, Part 1: Java classes and class loading

  •  Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.
  •  Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true
  • Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

The flow of loadClass() is as follows: 

  • Verify class name.
  • Check to see if the class requested has already been loaded.
  • Check to see if the class is a "system" class.
  • Attempt to fetch the class from this class loader's repository.
  • Define the class for the VM.
  • Resolve the class.
  • Return the class to the caller.

Java programming dynamics, Part 1: Java classes and class loading: "There are many circumstances where multiple application classloaders are used by Java programs. One example is within the J2EE framework. Each J2EE application loaded by the framework needs to have a separate class loader to prevent classes in one application from interfering with other applications. The framework code itself will also use one or more other class loaders, again to prevent interference to or from applications. The complete set of class loaders make up a tree-structured hierarchy with different types of classes loaded at each level."

Sunday, March 6, 2011

In and out

In and out: "

That's one of the most important decisions you'll make today.


How much time and effort should be spent on intake, on inbound messages, on absorbing data...


and how much time and effort should be invested in output, in creating something new.


There used to be a significant limit on available intake. Once you read all the books in the college library on your topic, it was time to start writing.


Now that the availability of opinions, expertise and email is infinite, I think the last part of that sentence is the most important:


Time to start writing.


Or whatever it is you're not doing, merely planning on doing.



"