Tuesday, November 20, 2012

Cryptography

Symmetric Encryption vs Asymmetric Encryption

Symmetric Encryption works by encrypting a message file by using a private key. The content can be decrypted using the same private key. If both the parties have the same key then only the message can be encrypted/decrypted.
Asymmetric Encryption works with the public key and private key combination.Any message/file encrypted using a public key can only be decrypted using the related private Key. Similarly the message which is encrypted using a private key key can only be decrypted using the related public key.

Digital Certificates is  a way of storing the keys and authenticating them through a neutral vendor, like Thawte, Symantec.


Tuesday, November 13, 2012

Hibernate Locking Strategies


Association Fetching

We can fetch the associated entities wither eagerly or lazily. The fetch parameter can be set to FetchType.LAZY or FetchType.EAGER. EAGER tries to use outer join select to retrieve the associated object, while LAZY is triggers a select when the associated object is accessed for the first time. @OneToMany and @ManyToMany are defaulted to LAZY, and @OneToOne and @ManyToOne are defaulted to EAGER. The recommended approach is to use LAZY on all static fetching definitions and override this choice dynamically through JP-QL. JP-QL has a fetch keyword that allows you to override laziness when doing a particular query. This is very useful to improve performance and is decided on a use case to use case basis.

Named Queries

Though we can write queries in the code, externalizing them makes the code cleaner. - it eases debugging - Named queries are precompiled by Hibernate at start up time. Unfortunately, you lose the type-safety of queries written using the Criteria API.


Hibernate Locking Strategies
Optimistic Locking

Optimistic locking is a technique where you allow your application to perform updates hoping there won't be any simultaneous updates from another process, hence optimistic. Pessimistic locking is the technique where you assume there will be simultaneous updates from another process so you lock the data you are changing before any changes take place.
In Hibernate, optimistic locking is provided fairly seemlesly. You add a version field to your table and a version element to your mapping file. When you update a Hibernate object Hibernate will check the version values match. If they do the update is successful, and the version is incremented, if they are not Hibernate throws a StaleObjectException and you know that something else has updated your data. 


Pessimistic Locking'


Pessimistic locking is provided by specifying a LockMode when you get an object from the database. If you get your object with the LockMode.UPGRADE for example Hibernate will use database specific SQL to lock the record (if your database supports it) such as "select ... for update". Now nothing can update that record till you are finished.


Hibernate Fetching Strategies

Pessimistic Concurrency Control 

Hibernate assumes that two or more users want update the same record at the same time, so it prevents that by placing locks on the records. The lock is placed as soon as the any piece of row is accessed. other users might be able to read the data even though a lock has been placed.

Optimistic Concurrency Control

Instead of placing the lock on the whole record every time that is read, the system merely looks for an indication that two users actually did try to update the same record at the same time. If that evidence is found , then one user's updated are discarded and the user is informed. Hibernate maintains this using version on the columns. Each time the server reads a record to try to updates the server makes a copy of the version number of the record and stores that copy for later reference. When it is time to update the data back to the disk, the server compares the original version number that is read against the version number that the disk drive now contains. - a) If the version numbers are the same, no one else changed the record and the system can write the updated value. b) If the Originally read value and the current value on the dist are not the same, then someone changed the data since it was read, and the current operation is probably out of date. Thus the system discards the version of the data and gives the user an error message. Each time a record is updated, the version number is updated as well.

Sunday, August 26, 2012

Tomcat Configuration


1) Stop/Start tomcat in one step This step will enable the users to stop and start tomcat in a single step. shutdown.bat && startup.bat

Tuesday, August 21, 2012

Databasse Interview Questions


1) Delete vs Truncate vs Drop Delete deletes all/ a few the records of the table. Truncate deletes all the records of the table, where as drop deletes the table and any indexes,privileges associated with the table. Delete is a DML operation, takes more time as it can be rolled back so will store the data in the undo space where as Truncate and Drop are DDL statements and can not be rolled back, so they are faster. From Oracle 10 the database tables can be undroppped. FLASHBACK TABLE TABLE_NAME TO BEFORE DROP;
2) SQL Joins can be classified into Equi join and Non Equi join. 1) SQL Equi joins It is a simple sql join condition which uses the equal sign as the comparison operator. Two types of equi joins are SQL Outer join and SQL Inner join. For example: You can get the information about a customer who purchased a product and the quantity of product. 2) SQL Non equi joins It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <, >=, <=
STORED PROCEDURE VS FUNCTION
IN functions we can not alter database records., can not use statements like insert, update, or delete. However we can perform the same functions in a stored procedure, so use stored procedure when the statements involve these kind of operations. Unlike stored procedures functions can be used to inline in SQL statements, other functions or in procedures so use it when you need to compute some value that will be later used in some SQL statement. Both stored procedure and function can be used to achieve the same goal.


3) Select top 3 rows/ select top row/ select row with maximum value/frequency
Suppose the table named, STREET is like below.

55 2ndstreet 555 57
59 2ndstreet 555 61
63 2ndstreet 555 22
65 1ststreet    555  21
67 2ndstreet 555 69
73 2ndstreet 555 75
77 3rdstreet 555 79
81 2ndstreet 555 83
105 4thstreet 555 107
133 2ndstreet 555 135

This Query gives the maxim/max frequently occuring column.
Query

select *  from (select street_name,count(street_name) from street group by street_name order by count(street_name) desc)  where rownum=1;



Thursday, August 16, 2012

Core Java Interview Questions

1) Is Java Compiled or Interpreted languages? Java is both, first it is compiled by Java Compiler into ByteCode(which is a form of machine language just for the JVM). Then JVM interprets this byte code and converts it into machine understandable language.


2) How JVM Memory is organized? Which are stored in which part of JVM Memory? Classes and Methods are stored in Perm Gen space. String internalized are also stored in Perm Gen space. This space is very limited compared to the HeapSize.

3) Difference between PrintWriter and Buffered Writer PrintWriter is used for small and dirty applications where we can display/write the messages on to the console. More over PrintWriter swallows the exceptions, later can read the exceptions by calling checkError() method.

4) Difference between BufferedWriter vs FileWriter BufferedWriter stores the data in the buffer and won't make those many calls to the operating system, it also lets us to specify the size of the buffer, if the buffer size is same/more than the streambuffer, the data is directly written into the file system.

5) Difference between FileWriter vs FileOutputStream Per java specification, use FileWriter to write the character data, and use FileOutputStream to write the raw byte data like images. Internally the FileWriter has to convert the character data into bytes which may reduce the performance. Also FileWriter can not properly handle raw data like images.

6) Convert Java Object JSON and Vice versa /** * */
 package com.hello.one;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileReader;
import java.io.FileWriter;
 import org.apache.log4j.Logger;
 import com.google.gson.Gson;

 class Sample {
 public int getId() { return id; }

 public void setId(int id) { this.id = id; }
 public int getAge() { return age; }

 @Override public String toString() { return "Sample [id=" + id + ", age=" + age + ", name=" + name + "]"; }
 public void setAge(int age) { this.age = age; }
 public String getName() { return name; }
 public void setName(String name) { this.name = name; }
 private int id;
 private int age;
 private String name;

 public Sample(int id, int age, String name) { super(); this.id = id; this.age = age; this.name = name; } }

/** * @author kiran * */

public class JSONTest {

 private static final Logger log = Logger.getLogger(JSONTest.class.getName());
 /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub
 Sample s1 = new Sample(1,25,"Kiran");
 Sample s2 = new Sample(2,30,"Rams");
 Gson gson = new Gson();
 String json1 = gson.toJson(s1);
 String json2 = gson.toJson(s2);
 String jsonFilePath = "simple.json";
 File file = new File(jsonFilePath);
 try {
 FileWriter fw = new FileWriter(file);
 BufferedWriter bwr1 = new BufferedWriter(fw);
 bwr1.write(json1);
 bwr1.write(json2); //fw.write(json); // fw.close(); bwr1.close();
 log.info("Saved the json file to the file simple.json");
 System.out.println("Json file outout : "+ json1+" "+ json2);
 log.info("Now Reading the contents from JSON file simple.json");
 FileReader reader = new FileReader(file);
 BufferedReader br = new BufferedReader(reader);
 FileWriter outFile = new FileWriter("outfilejson.txt");
 int length = 0;
 BufferedWriter bw2 = new BufferedWriter(outFile);
 String bufLine = null;
 while((bufLine = br.readLine())!= null) {
 log.info("Writing the line using the BufferedOutputStream : "+ bufLine); bw2.write(bufLine); } /* while((length=reader.read())!=-1)
{  System.out.println("writing the char/int :"+ length); outFile.write((length)); } */ /* reader.close(); outFile.flush(); outFile.close();*/ bw2.close(); br.close(); }
 catch(Exception ex) {
 ex.printStackTrace();
 } } }

 7) Java Classloaders Java classloader is the key component of the Java Virtual Machine(JVM). A class file contains the byte code and references to other classes. Classloader identifies the byte code of the class and creates the instance of the java.lang.Class class, this makes this class available for the JVM for execution. JVM follows lazy loading of the classes,as it does not need to which classes get loaded during run time. Java classloaders have a hierarchy, when ever a class needs to be loaded, the resposibility is delegated to its parent classloader. Bootstrap class loader is at the top of the list. Bootstrap class loader loads the java2 core classes, Application classes are loaded by System Class loaders. Each class loader has a parent class loader except Bootstrap class loader. When the client requests a class, that class is loaded if it has been previously loaded by the jvm, jvm caches each class that is loaded previously. If the class is not loaded already the request is delegated to the parent class loader u pto Bootstrap classloader. If the parent class loader fails to load a class, then the current class loader tries to load this class. If the class is not found, then java.lang.ClassNotFoundException is thrown. We can write our own custom class loaders. With Custom Class loaders we can customize the behavior of the class loaders, like calling the parent class loaders when a class is requested. We can override this behaviour, example- all the web/application containers have their own implementation of the classloader, because of that only webapplication is able to use different versions of jarfiles/classes from what is contained in the web/application server. If the same class is loaded by two different class loaders and we try to compare them will cause ClassCastException. We need custom class loaders to control the JVM behavior of loading classes. Classloader Hierarchy - BootStrap ClassLoader->Ext ClassLoader-> App ClassLoader.

8) ClassNotFoundException vs NoClassDefFoundError ClassNotFoundException is a checked exception and NoClassDefFoundError is the error type. Both of these are related to the unavailability of the required class during runtime. ClassNotFoundException occurs when the JVM/classloader tries to load a class and the class definition is no longer found. If a class is loaded by two different class loaders and we try to access the class which is loaded by a different classloader, then we get ClassNotFoundException. ClassNotFoundException occurs bacause of the explicit loading of the class using , Class.forName(), ClassLoader.loadClass()... NoClassDefFoundError occurs when the class exists during compile and not found during run time, it could happen because the class is loaded by two different class loaders and proper class is not found.

9) When to use extends Class and When to use implements Interface Use Interface when there is a chance of several changes to your code. Use extends Class when there is some default implementation of a class that can be used by the child classes. Also to be able to extend other classes, go for implementing the interface that way You can extend the other classes.

10) Java Memory issues or Production issues DB --- Database indexes are not created properly. Stale data is not cleared in DB. Application ------------ Synchronization is not handled properly in the java application, should consider using synchronization when using non-threadsafe collections like Hash Map, otherwise you may get corrupted data or infinite loops. Use synchronization carefully, over usage may degrade the application performance. Handle proper communication with external systems like giving optimal time out for JMS, Web Service calls, also consider using Asynchronous communication instead of Synchronous communication wherever applicable. Handle Java Memory leaks properly, with Code reviews, static code analysis. Study the HeapDump and ThreadDump to study how the application is doing. Introduce Proper Chaching to the appliaction to improve performance. Excessive Caching can also lead to fill the Heap size and degrade the performance and may force many garbage collection cycles. Proper monitoring of the application using Heap/Thread dumps can also help to prevent the production issues.

11) Comparable vs Comparator in Java By implementing Comparable you can compare/sort the class objects using compareTo() method, this is done based on the natural ordering. It can be achieved using by Collectoions.sort(). Java Wrapper classes by default implement the Comparable interface, so their objects stored in collections can be sorted using Collections.sort(ArrayList), or Arrays.sort(). The sorting is based on the natural ordering of the elements. The objects that implement Comparable can be used as keys in TreeSet or SortedSet without specifying any Comparator. So if we want to sort the elements based on their natural ordering go for Comparable, otherwise if want to compare objects based on some other attributes use Comparator. Also when you are not the original author of the class, then you can not  make the class implement Comparable, then the only choice is implementing Comparator. By implementing Comparator you can compare/sort the class objects using compare() method, this is based on the order/implementation that we defined in the Comparator implementation.

12) Equals and HashCode in Java The general contract is that if two objects are equals as per the equals method,they should have the same hashcode value, and if two objects are different they may or may not the same hashcode. When ever you want to keep the objects in HashMap, you should override the equals method from Objects class, the default implementation of Object's equals method checks whether these two instances point to the same object or not i.e., same as compares them using ==. Whenever you overwrite the equals method, should overwrite hashcode as the java specification says that two equals objects should have equal hashcode value.

13) Singleton vs Static classes in Java Singleton makes sure that only one object of the class is created any time, where as static class can have multiple instances. Singleton can do lazy initialization of the instance where as the Static class can only do early initiliazation of the Object.

14) Java Memory Management - How the Objects are stored in Memory? How Java Memory is shared? When ever you create a new object something like Test t = new Test(), this object is stored in Heap. Whenever a String is created using a literal or intern that is created in the PermGen space. 15) Race condition in Multi threading This happens when two or more threads operating on an object and some of them can not see the changes done by the other threads. Typical example is Singleton creation, that is before creating the instance we check if the object is null, if two threads see that condition, they may create two singleton objects. Race condition can be prevented by making the block/method synchronized and ensure locking. Also it can be prevented by using Atomic variables like AtomicInteger, whose operations are atomic, where as prior to jdk1.5 anyvariable++ is not atomic, it is a combination of 3 atomic operations(read,update, and write).

16) How Thread join works Thread join lets one thread to make other thread to complete. If t is thread then t.join() lets the current thread to pause execution until thread t completes.

17) Liveness, Deadlock, Livelock, Starvation A concurrent application's ability to execute in a timely manner is called Liveness.The most common Liveness problems are DeadLock,LiveLock, and Starvation. DeadLock - DeadLoack is a situation where two are more threads are blocked forever waiting for action from other Threads. Starvation and Livelock are less likely to occur than a Deadlock. Starvation occurs if a greedy thread takes more time by invoking a synchronized method frequently and other threads spend most of the time waiting for the lock to be released. Livelock - A thread acts in response to other thread's actions, and the other thread also waits for a response from some other thread then it becomes a livelock. Just like Deadlock, here also threads can not make any progress, they are not blocked by each other but too busy responding to other thread to resume work.

18) Lock and ReentrantLock Lock and Reentrant lock are used in place of synchronization to solve concurrency issues. These are also based on synchronization but provides more control to the appliaction like tryLock() method backs out if the lock is not available immediately. LockInterruptibly method backs out of another thread sends interrupt before the lock is acquired.

19) Atomic Variables We can avoid unnecessary synchronization using Atomic Variables, the operations on these variables are atomic like AtomicInteger ai = new AtomicInteger(6); ai.incrementAndGet(), ai.decrementAndGet().

20) Executors Service Executors Service provides three implementations SingleThreadExecutor FixedThreadPool ScheduledThreadPool When you are done with the ThreadPoolExecutor, you must shut it down otherwise running thread will prevent the JVM from shutting down. shutdown() will not shutdown the ThreadPoolExecutor immediately, but will not accept any new thread connections, it will shut down when all the threads in this pool complete execution. If you want to shutdown the executor without worrying about the inprocess thread use shutdownNow(), this will not guarantee that existing threads will complete processing.

21) LinkedHashMap and ConcurrentHashMap LinkedHashMap is used in LRU cache implementations, it maintains the keys in the accessing order rather than in the inserint order. removeEldestEntry() method helps to remove the least recently used element from the Cache. ConcurrentHashMap is used in multithreaded applications where there are one/ a few writers and more Readers. ConcurrentHashMap doesn't synchronize read method, does only on write() method.