Friday, February 8, 2013

How to Avoid DeadLock in Mutithreading....??


Deadlock Scenario:
 public void method1(){
         synchronized(String.class){
             System.out.println("Aquired lock on String.class object");
             synchronized (Integer.class) {
                 System.out.println("Aquired lock on Integer.class object");
             }
         }
    }

    public void method2(){
        synchronized(Integer.class){
            System.out.println("Aquired lock on Integer.class object");
            synchronized (String.class) {
                ,System.out.println("Aquired lock on String.class object");
            }
        }
    }


No Deadlock Scenario:
 
    public void method1(){
        synchronized(Integer.class){
            System.out.println("Aquired lock on Integer.class object");
            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }

    public void method2(){
        synchronized(Integer.class){
            System.out.println("Aquired lock on Integer.class object");
            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }

So here we clearly sees that Consistent lock acquisition ordering prevents deadlock. That is the simplest and most efficient way to avoid deadlock is to ensure that resources are always acquired in some well-defined order.

Why Wait() , Notify() and NotifyAll() is defined in Object Class..

This is one of most common interview question in java threading and many of us know the answer but couldn't be able to explain properly.
Here what I say..  Since wait, notify, notifyAll manipulates the LOCK, which is part of Object i.e thread takes or release the lock, which is part of Object/Class in java.  and these methods manipulate the lock, this is why they are defined at Object Class.

That's the reason we can call wait(), notify(), notifyAll() only within synchronized block/method. If you call wait( ) or notify( ) within a method that’s not synchronized, the program will compile, but when you run it you’ll get an IllegalMonitorStateException with the somewhat non-intuitive message “current thread not owner.”
Note that sleep( ), suspend( ), and resume( ) can all be called within non- synchronized methods since they don’t manipulate the lock.

In nutshell, Locks are made available on per Object basis i.e. any Object can be the monitor for a thread. The wait and notify are called on the monitor. The running thread checks with the monitor. So the wait and notify methods are in Object and not Thread.

Another reason for putting wait and notify could be that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized

Monday, January 16, 2012

Cache Implementation in JAVA


A lot of us heard the word cache and when you ask them about caching they give you a perfect answer but they don’t know how it is built, or on which criteria I should favor this caching framework over that one and so on, in this article we are going to talk about Caching, Caching Algorithms and caching frameworks and which is better than the other.

The Interview:

"Caching is a temp location where I store data in (data that I need it frequently) as the original data is expensive to be fetched, so I can retrieve it faster. "
That what programmer 1 answered in the interview (one month ago he submitted his resume to a company who wanted a java programmer with a strong experience in caching and caching frameworks and extensive data manipulation)
Programmer 1 did make his own cache implementation using hashtable and that what he only knows about caching and his hashtable contains about 150 entry which he consider an extensive data(caching = hashtable, load the lookups in hashtable and everything will be fine nothing else) so lets see how will the interview goes.

Interviewer: Nice and based on what criteria do you choose your caching solution?
Me:huh, (thinking for 5 minutes) , mmm based on, on , on the data (coughing…)
Interviewer: excuse me! Could you repeat what you just said again?
Me: data?!
Interviewer: oh I see, ok list some caching algorithms and tell me which is used for what
Me: (staring at the interviewer and making strange expressions with his face, expressions that no one knew that a human face can do :D )
Interviewer: ok, let me ask it in another way, how will a caching behave if it reached its capacity?
Me: capacity? Mmm (thinking… hashtable is not limited to capacity I can add what I want and it will extend its capacity) (that was in Memind he didn’t say it)
The Interviewer thanked Me(the interview only lasted for 10minutes) after that a woman came and said: oh thanks for you time we will call you back have a nice day This was the worst interview Mehad (he didn’t read that there was a part in the job description which stated that the candidate should have strong caching background ,in fact he only saw the line talking about excellent package ;) )




Sunday, June 19, 2011

Interview SQL queries

1.   Find the Duplicate records in table.
 
   1. SELECT email, COUNT(email) AS NumOccurrences
FROM T 
GROUP BY email HAVING ( COUNT(email) > 1 ) ;
  
 2. SELECT * FROM emp a
     WHERE rowid = ( SELECT max(rowid) FROM emp
                            WHERE empno = a.empno
                            GROUP BY empno 
HAVING count(*) >1)



2.   Delete Duplicate records from table.
    1.  DELETE FROM table_name A 
WHERE ROWID > (SELECT min(rowid) 
FROM table_name B  
WHERE A.key_val = B.key_val);


    2. 


1.   Find the Duplicate records in table.





















Consider the below DEPT and EMPLOYEE table and answer the below queries.
DEPT
DEPTNO (NOT NULL , NUMBER(2)),
DNAME (VARCHAR2(14)),
LOC (VARCHAR2(13)

EMPLOYEE
EMPNO (NOT NULL , NUMBER(4)),
ENAME (VARCHAR2(10)),
JOB (VARCHAR2(9)),
MGR (NUMBER(4)),
HIREDATE (DATE),
SAL (NUMBER(7,2)),
COMM (NUMBER(7,2)),
DEPTNO (NUMBER(2))

MGR is the EMPno of the Employee whom the Employee reports to.DEPTNO is a foreign key
1. List all the Employees who have at least one person reporting to them.</span><br /> 

SELECT ENAME FROM EMPLOYEE WHERE EMPNO IN (SELECT MGR FROM EMPLOYEE); 

2. List the highest salary paid for each job.

SELECT JOB, MAX(SAL) FROM EMPLOYEE GROUP BY JOB

3. In which year did most people join the company? Display the year and the number of Employees 
SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR", COUNT(EMPNO) "NO. OF EMPLOYEES"
FROM EMPLOYEE
GROUP BY TO_CHAR(HIREDATE,'YYYY')
HAVING COUNT(EMPNO) = ( SELECT MAX(COUNT(EMPNO))
FROM EMPLOYEE
GROUP BY TO_CHAR(HIREDATE,'YYYY'));
  
4.  Write a correlated sub-query to list out the Employees who earn more than the average salary of their department. 
SELECT ENAME,SAL
FROM EMPLOYEE E
WHERE SAL &gt; (SELECT AVG(SAL)
FROM EMPLOYEE F
WHERE E.DEPTNO = F.DEPTNO);

5. Find the nth maximum salary.  
SELECT ENAME, SAL
FROM EMPLOYEE A
WHERE &N = (SELECT COUNT (DISTINCT(SAL))
FROM EMPLOYEE B
WHERE A.SAL <=B.SAL);  

6. Select the duplicate records (Records, which are inserted, that already exist) in the EMPLOYEE table.  
SELECT * FROM EMPLOYEE A
WHERE A.EMPNO IN (SELECT EMPNO                                        
FROM EMPLOYEE                                        
GROUP BY EMPNO                                          
HAVING COUNT(EMPNO)> 1)
AND A.ROWID!=MIN (ROWID));


7.  Write a query to list the length of service of the Employees (of the form n years and m months).
SELECT ENAME "EMPLOYEE",
        TO_CHAR(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12))
||' YEARS '|| TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN
(SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH OF SERVICE"
FROM EMPLOYEE;



Friday, June 3, 2011

Joseph Problem...

Joseph likes taking part in programming contests. His favorite problem is, of course, Joseph's problem. It is stated as follows.


Problem : There are n persons numbered from 0 to n - 1 standing in a circle. The person number k, counting from the person number 0, is executed. After that the person number k of the remaining persons is executed, counting from the person after the last executed one. The process continues until only one person is left. This person is a survivor. The problem is, given n and k detect the survivor's number in the original circle.
  Solution: You can easily write a recursive write:
 Example:(20, 3) = 4+17-1 =20 Find J (20, 3), assume that you have to know the J (19, 3) = 17, then remove the number 3 20 people who left with 19 people, and this 19 starting from the number 4, 17 the last person is left, so J (20, 3) = 4 +17-1 = 20
 
public class JoshephProblem {
    public static void main(String[] args) {
        System.out.println(">>> " + J(5, 3));
    }

    public static int J(int n, int m) {
        if (n == 2) {
            if (m % 2 == 1)
                return 2;
            else
                return 1;
        } else {
            int temp = (J(n - 1, m) + m) % n;
            if (temp == 0)
                return n;
            else
                return temp;
        }
    }
}

Monday, May 23, 2011

Why Marker Interface ?

he main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementer of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.


When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException
Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation.
So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality. 

public Object clone() throws CloneNotSupportedException {

 if (this implements Cloneable)

     return nativeCloneImpl();

 else

     throw new CloneNotSupportedException();

}
 
Can anyone tell why and when do we get 'CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for Cloneable or any other standard marker interface for that matter.


user-defined marker interface in Java:-
to be continued........ 



Wednesday, April 27, 2011

DB Indexes

Q. What's DB indexes ?
A. basically used to sort data in a table.
There are basically 2 types of DB indexes:- Clustered and non-clusterd

Q. What's Mean By Cluster?
A. Oracle cluster supply an optional way of storing table data. In a cluster a group of tables share the same data blocks. The tables are grouped together because they share identical columns and are often used together. For example, the employee and department table use the depth no column. When you cluster the employee and department tables Oracle Database physically stores all rows for each department from both the employee and department tables in the same data blocks.
A cluster is used in database so that to keep all the rows of all data tables together and they can easily be accessed by the help of shared cluster key.

Because clusters store relevant rows of dissimilar tables together in the one data blocks, correctly used clusters offer two primary benefits:
■ Disk I/O is condensed and access time improves for joins of clustered tables.
■ The cluster key is the column, or collection of columns, that the clustered tables have
in same. You identify the columns of the cluster key when creating the cluster.
You next specify the same columns when creating every table added to the cluster. Each cluster key value is saved only single time each in the cluster and the cluster index, no concern how many rows of different tables hold the value.

Q. What's Cluster and Non-Cluster Indexes ?

A clustered Index sort the data in a table physically.
A non-clustered Index doesn't sort the data physically.

As clustered Index sort the data physically, So there can be only one Clustered index per table.
where as there can be many non-clustered index in table.
(with a maximum of 255 such indexes per table a very authentic possibility. i.e. every single column can be utilize for non-cluster indexing )

Q. when you can use a clustered or a non clustered index????
A. The clustered is a safe bet if you are working with a table having a large number of unique data, such as a table containing the employee IDs for the different members of an organization. These IDs are always unique, and using a clustered index is a good way of retrieving this large volume of unique data rapidly. On the other hand, a non clustered index is the best approach if you have a table that does not contain too many such unique values. These are just some of the differences between the two. You can read in detail about these differences by putting a search on the Internet for the differences between the two.

- - - - - -- - - - -- - - -