Thursday, November 4, 2010

Difference between Alias and Synonym

An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location qualifier of a table or view. Sysnonym can be used for the user who created it. But alias can be used for any users. Synonym is dropped when base table got dropped but alias will not get dropped. Synonym is recorded in the sys.synonym table and alias is recorded in sys.tables.

Tuesday, November 2, 2010

Difference between NoClassDefFoundError & ClassNotFoundException

java.lang.NoClassDefFoundError is thrown when we try create an object of a class and the runtime environment is not able to load the given class. This happens when we create the object using the new operator. The searched class though existed when the calling class was compiled but at run time the classloader wasn't able to find the binary code.

java.lang.ClassNotFoundException is thrown when a class is being loaded by the class loader. The class is presumed to be present in any the jar files located in the classpath,or lib. This exception is thrown when the forName method in the class or the findSystemClass/loadClass methods in the ClassLoader is being used.

The following program demonstrates the two , the first method createNew throws the NoClassDefFoundError and the second method loadClass throws ClassNotFoundException.


public class TestException {
public static void main(String[] args) {
createNew();
loadClass();
}
private static void createNew(){
FirstClass fc= new FirstClass();
}
private static void loadClass(){
try {
Class cla11 = Class.forName("collectionsTest.FirstClass");
FirstClass firstClass = (FirstClass)cla11.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


A very good post on this is provided here

SQL Basics - 2

ALTER Command :

The structure of the table can be modified by the alter command. Not only the structure but also columns can be added,deleted,data type modified, renamed with the alter table. Also Indexes, constraints can be added,deleted or modified.

ALTER table works by making a temporary copy of the original table. The alteration is performed on the copy , then the original table is deleted and the new one is renamed. While Alter table is executing , the original table is still readable to other oracle users.

Alter table ACCNTS ADD(user_lname varchar2(40), inst_dt date)

DB2 version : Alter table ACCNTS ADD column lname varchar(40)

Alter table ACCNTS DROP COLUMN inst_dt (in DB2 its not possible to drop a column from a table)

Alter table ACCNTS MODIFY (user_lname varchar2(100)) , this statement can modify both the data type and size

DB2 : Alter table ACCNTS alter column lname SET DATA TYPE varchar(200)


RENAME TABLE:

rename table ACCNTS to ACCOUNTS

TRUNCATE TABLE:

truncate table ACCNTS1

Truncate operations drop and re create the table which is much faster than deleting rows one by one
There is no truncate command in DB2, so the equivalent command in DB2 is

alter table accnts1 activate not logged initially with empty table;

DROP TABLE:

drop table ACCNTS1

SYNONYMS:

A synonym is an alternative name for objects such as tables,views , sequences

create or replace public synonym Chulbul for accnts.

(please check another post for difference between synonym and alias)

we can create synonym of any object from table,views,sequence,stored procs, functions even other synonymns. The synonym can also be dropped similar way

drop public synonym Chulbul


Monday, November 1, 2010

SQL Basics - 1

One Language that I have been using from my first project till this very day and still have no clue about is PL/SQL. So without wasting much time i would like to jump into the nitty gritties of core PL/SQL commands. I have Oracle 10g and DB2 EXPRESS C installed in my machine and using TOAD for oracle/DB2 for executing the commands. If a certain command is specific to Oracle or DB2 i will highlight the same.

Create Command :(DDL script)

create table ACCNTS (accnt_no number(16), accnt_name varchar2(100), balance number(10,2))

This will create an ACCNTS table with accnt_no, accnt_name, balance columns.

The equivalent command in DB2 would be

create table ACCNTS (accnt_no numeric(16), accnt_name varchar(100), balance numeric(10,2))

as number and varchar2 are not valid datatypes in db2

INSERT Command : (DML script)

insert into ACCNTS (accnt_no,accnt_name, balance) values (1, 'tatha', 10.00)

this command will insert the said values in the ACCNTS table. Its not necessary to give the column names as we are inserting all the values. If we choose not to insert all the values then we have to mention the column names and its not bound by any order.

It is also possible to insert data

SELECT Command : (DML script)

select * from ACCNTS or select accnt_no,accnt_name from ACCNTS.

This very obvious what this command will do.

WHERE Clause :

the where clause acts as a filter criteria

select * from ACCNTS where accnt_no > 10 or
select accnt_no from ACCNTS where accnt_name='tatha'

DELETE Command :

To delete all the rows of a table the command

delete from ACCNTS , for selective deletion the where clause can be used
UPDATE Command :

To update the values in a table the update command is used

update ACCNTS set accnt_name = 'Roy' where accnt_no=11

DISTINCT Clause :

distinct can be used when we require to eliminate duplicates. Suppose we have two records in the ACCNT table with name as tatha, and we want to view distinct names, the query is

select distinct accnt_name from ACCNTS

ORDER BY Clause :

To order the result we use the ORDER BY clause. The order can be both DESC and ASC. Suppose we want to order the balance in a descending order

select * from ACCNTS order by balance desc;

AS SELECT Clause
It is also possible to create a table from the data of another table, for example if we want to create a table ACCNT_DET which has accnt_no and accnt_name from ACCNTS

create table ACCNT_DET (accnt_no,accnt_name) as select accnt_no, accnt_name from ACCNTS

This command doesnt work in DB2 database, the equivalent command in DB2 database consists of two commands

Create table new_table like old_table;
Insert into new_table select * from old table

The second command can be used in Oracle to insert into a table values from another table like

Insert into ACCNT_DET select accnt_no_accnt_name from ACCNTS



Sunday, October 31, 2010

Atomicity

What happens when we add one element of state to what was a stateless object? Suppose we want to add a "hit counter" that measures the number of requests processed. The obvious approach is to add a long field to the servlet and increment it on each request.

public class UnsafeCountingFactorizer implements Servlet {

private long count = 0;

public long getCount() {

return count;

}

public void service(ServletRequest req, ServletResponse resp) {

BigInteger i = extractFromRequest(req);

BigInteger[] factors = factor(i);

++count;

encodeIntoResponse(resp, factors);

}

}

Unfortunately, UnsafeCountingFactorizer is not thread-safe, even though  it would work just fine in a single-threaded environment. It is susceptible to lost updates. While the increment operation,  ++count, may look like a single action because of its compact syntax,  it is not atomic. shows what can happen if two threads try to increment a counter simultaneously  without synchronization. If the counter is initially 9, with some unlucky timing  each thread could read the value, see that it is 9, add one to it, and each set  the counter to 10. This is clearly not what is supposed to happen; an increment  got lost along the way, and the hit counter is now permanently off by one. This is known is Race Condition.

UnsafeCountingFactorizer has several race conditions that make its results unreliable. A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime; in other words, when getting the right answer relies on lucky timing.

Race Condition can be avoided by lazy initialization

public class LazyInitRace {

private ExpensiveObject instance = null;

public ExpensiveObject getInstance() {

if (instance ==null){

instance = new ExpensiveObject();

}

return instance;

}

}

LazyInitRace has race conditions that can undermine its correctness. Say that threads A and B execute getInstance at the same time. A sees that instance is null, and instantiates a new ExpensiveObject. B also checks if instance is null. Whether instance is null at this point depends unpredictably on timing, including the vagaries of scheduling and how long A takes to instantiate the ExpensiveObject and set the instance field. If instance is null when B examines it, the two callers to getInstance may receive two different results, even though getInstance is always supposed to return the same instance.

If the increment operation in UnsafeSequence were atomic, the race conditioncould not occur, and each execution of the increment operation would have the desired effect of incrementing the counter by exactly one. To ensure thread safety, check-then-act operations (like lazy initialization) and read-modify-write operations (like increment) must always be atomic. Atomic state can be created by the syncronization or the free atomic package in new Java 1.5

public class CountingFactorizer implements Servlet { 
    private final AtomicLong count = new AtomicLong(0); 
     public long getCount() {
       return count.get(); 
     } 
 public void service(ServletRequest req, ServletResponse resp) {                                
         BigInteger i = extractFromRequest(req);    
         BigInteger[] factors = factor(i);
         count.incrementAndGet();
         encodeIntoResponse(resp, factors);
     }
 } 


The java.util.concurrent.atomic package contains atomic variable classes for effecting atomic state transitions on numbers and object references. By replacing the long counter with an AtomicLong, we ensure that all actions that access the counter state are atomic. Because the state of the servlet is the state of the counter and the counter is thread-safe, our servlet is once again thread-safe.We were able to add a counter to our factoring servlet and maintain thread safety by using an existing thread-safe class to manage the counter state, AtomicLong. When a single element of state is added to a stateless class, the resulting class will be thread-safe if the state is entirely managed by a thread-safe object. But, as we'll see in the next section, going from one state variable to more than one is not necessarily as simple as going from zero to one.

Where practical, use existing thread-safe objects, like AtomicLong, to manage your class's state. It is simpler to reason about the possible states and state transitions for existing thread-safe objects than it is for arbitrary state variables, and this makes it easier to maintain and verify thread safety.

Friday, October 29, 2010

Difference between Encapsulation & Abstraction

This is a common OOPS related question that is being regularly asked in interviews and though it seems to have an easy answer to it, the actual difference can be a bit tricky. So I thought of just pointing out the main differences that i came to understand.

Encapsulation : In simple words , Encapsulation is data hiding. One of the major fundamentals of a good java design is that a class should have 'low coupling, high cohesion'. To have a low coupling, the calling class should be less dependent on the properties of the class or to say if the property changes it shouldn't change the depending functionalities. Encapsulation also prevents direct data manipulation by hiding the property and only which can be accessed by accessor methods. P.J. Plauger has a great analogy and definition of information hiding.”Information hiding is not the same as secrecy. The idea is not to prevent outsiders from knowing what you are doing inside a module. Rather, it is to encourage them not to depend on that knowledge. That leads to a kind of secondary coupling which is more pernicious than obvios dependency because it is less visible. You should encapsulate information to keep it private, not secret. (What you do in the bathroom is no secret, but it is private.)”

Abstraction : Abstraction is the interface which hides the inner functionality.Let’s compare Java and C++. We have a good example of abstraction. In C++, you have to deal with pointers and references a lot. You have to deal a lot of garbage collection. In essence, you have to work on a low level. (C and C++ in turn abstracted a lot of even lower level machine code.) In Java, those things are abstracted away. You just assume they exist. In essence, abstraction means that you are working on a higher level. You don’t care how pointers work in Java, you just assume that they work. You don’t have to concentrate on the lower level stuff, you work on higher level. Abstraction can be seen in java esp in the io package where how the string, or byte is being written in the output stream or read from the stream is not the developers concern

Thursday, October 28, 2010

Loopy Problem - IV

Provide declarations for i and j that turn this loop into an infinite loop:

while (i <= j && j <= i && i != j) { 
} 

The <= operator is still antisymmetric on the set of primitive numeric values, but now it applies to operands of boxed numeric types as well. (The boxed numeric types are Byte, Character, Short, Integer, Long, Float, and Double.) The <= operator is not antisymmetric on operands of these types, because Java's equality operators (== and !=) perform reference identity comparison rather than value comparison when applied to object references.

To make this concrete, the following declarations give the expression (i <= j && j <= i && i != j) the value true, turning the loop into an infinite loop:

Integer i = new Integer(0);

Integer j = new Integer(0);

The first two subexpressions (i <= j and j <= i) perform unboxing conversions [JLS 5.1.8] on i and j and compare the resulting int values numerically. Both i and j represent 0, so both of these subexpressions evaluate to TRue. The third subexpression (i != j) performs an identity comparison on the object references i and j. The two variables refer to distinct objects, as each was initialized to a new Integer instance. Therefore, the third subexpression also evaluates to true, and the loop spins forever.