Tuesday 5 May 2015

Check befire Down casting in Java

Before downcasting, check for the dynamic type of the object and then downcast.
StringBuffer str = new StringBuffer("Hello");
Object obj = str;
if(obj instanceof String)
{
String strBuf = (String) obj;
}

Daemon thread in Java

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running.
An example for a daemon thread is the garbage collection.
You can use the setDaemon() method to change the Thread daemon properties.

setDamon(boolean) can only be called before the thread has been started.
By default the thread inherits the daemon status of its parent thread.

  • When a new thread is created it inherits the daemon status of its parent.
  • Normal thread and daemon threads differ in what happens when they exit.                           When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound - JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.

public class DaemonTest
{
  public static void main(String[] args)
  {
     new WorkerThread().start();
     try 
     {
         Thread.sleep(7500);
     }
     catch (InterruptedException e)
     {}
    System.out.println("Main Thread ending") ;
  }
}

class WorkerThread extends Thread
{
  public WorkerThread()
  {
     setDaemon(true) ; // When false, (i.e. when it's a user thread), // the Worker thread continues to run. // When true, (i.e. when it's a daemon thread), // the Worker thread terminates when the main // thread terminates.
   }
   public void run()
   {
      int count=0 ;
      while (true)
     {
        System.out.println("Hello from Worker "+count++) ;
         try
        {
           sleep(5000);
        }
        catch (InterruptedException e)
        {}
     }
  }
}

Sorting Techniques use in Java

According to the Java 7 API doc for primitives:
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.
According to the Java 7 API doc for objects:
The implementation was adapted from Tim Peters's list sort for Python ( TimSort). It uses techniques from Peter McIlroy's "Optimistic Sorting and Information Theoretic Complexity", in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

Tricky SQL queries

In SQL, what is the difference between count(column) and count(*)?


count(*) counts NULLs and count(column) does not


create table ExampleTable(id1 int, id2 int)
insert ExampleTable values(null,null)
insert ExampleTable values(1,null)
insert ExampleTable values(null,1)
insert ExampleTable values(1,null)
insert ExampleTable values(null,1)
insert ExampleTable values(1,null)
insert ExampleTable values(null,null)

 select count(*),count(id1),count(id2) from ExampleTable
 results 7 3 2
  
It's worth mentioning that if you have a non-nullable column such as ID, then count(ID) will significantly improve performance over count(*)
  
Another minor difference, between using * and a specific column, is that in the column case you can add the keyword DISTINCT, and restrict the count to distinct values:
 Example 
select column_a, count(distinct column_b)
from table
group by column_a
having count(distinct column_b) > 1;

What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?

For example: I have a JOBS table with the column JOB_NUMBER.
How can I find out if I have any duplicate JOB_NUMBERs, and how many times they're duplicated?
Query: 
select column_name, count(column_name)
from table
group by column_name
having count (column_name) > 1;


How can a column with a default value be added to an existing
table
ALTER TABLE {TABLENAME}
 ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME}
DEFAULT {DEFAULT_VALUE}[WITH VALUES]

Class loader in Java

ClassLoaders(CL) in Java

Class Loader:

1. Responsible for loading classes
2. is Abstract class
3. given binary name -> CL should attempt to locate or generate data that    constitues a definition for the class
4. Every Class object contains reference to ClassLoader that defined it.
5. Class objects for array classes are not created by ClassLoader but automaticallt by Java runtime.   If the element type is a primitive type, then array class has no class loader.
6. Class.getClassLoader()
7. typically used by security managers to indicate security domains
8. ClassLoader class uses a delegation model to search classes and resources.   Each instance of ClassLoader has an assocaited parent class loader.
9. When requested to find a class or resource, a ClassLoader instance delegate the search for the class or resource to its parent class loader before attempting to find class itself.
10. Virtual machine build in class loader called "BootStrap class loader" does not ahve parent but may serve as parent of classloader instance.
11. Normally, JVM loades classes from local file system  in paltform dependent manner.
12. Some classes may not originate from a file, they may originate from other sources. The method defineClass converts bytes into an instance of class "Class". Instance of newly defined is class can be created using Class.newInstance.
13. Method and constructor of objects created by class loader may reference to other class.    JVM uses loadClass method of the classs loader that originally created the class.      

Layered Architecture V/S Tiered Architecture

Logical layers are merely a way of organizing your code.
Typical layers include Presentation, Business and Data – the same as the traditional 3-tier model. But when we’re talking about layers, we’re only talking about logical organization of code.
In no way is it implied that these layers might run on different computers or in different processes on a single computer or even in a single process on a single computer. All we are doing is discussing a way of organizing a code into a set of layers defined by specific function.

Physical tiers however, are only about where the code runs. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.

A "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code. You may say you have a "3-tier" system, but be running it on one laptop. You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database. There's power in precision.