Multi thread java interview questions

Multi thread java interview questions


1).What is Multithreading in java

ANS:   Multithreading in java is a process of executing multiple threads simultaneously.

         Thread is basically a lightweight sub-process, a smallest unit of processing.
          Multiprocessing and multithreading, both are used to achieve multitasking.


2).What is thread?Why we are using threads?
  ANS:
      thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

      Threads are independent, if there occurs exception in one thread, it doesn't affect other threads.
       It shares a common memory area.



3).What is the difference b/w Process and Thread in java?
  ANS:
  PROCESS:
   Each process have its own address in memory i.e. each process allocates separate memory area.
   Process is heavyweight.
   Cost of communication between the process is high.

  thread:

  thread is a lightweight sub process, a smallest unit of processing.
  It is a separate path of execution.
  Threads are independent, if there occurs exception in one thread,
  it doesn't affect other threads.
  It shares a common memory area.



4).How many ways to implement the thread in java?Which approach is best?Exaplin
  ans:
     There are two ways to create a thread:

    *  By extending Thread class
    *  By implementing Runnable interface.

     By extending Thread class

        Thread class provide constructors and methods to create and perform operations on a thread.
        Thread class extends Object class and implements Runnable interface.

    By implementing Runnable interface.

      The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
        Runnable interface have only one method named run().


ans:
                                implements Runnable     extends Thread
Inheritance option         extends any java class No
Reusability                             Yes        No
Object Oriented Design          Good,allows composition Bad
Loosely Coupled                             Yes        No
Function Overhead                     No                Yes




5).When to use Runnable and Thread?

ans:

You usually extend a class to add or modify functionality. ...
In the same light, if you don't need to inherit thread methods, you can do without that overhead by using Runnable.
Single inheritance: If you extend Thread you cannot extend from any other class, so if that is what you need to do, you have to use Runnable.

6).Explain thread methods?

     public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
   

7).Explain thread life cycle.
  ans:
  1) New

          The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

  2) Runnable

        The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

   3) Running

        The thread is in running state if the thread scheduler has selected it.

    4) Non-Runnable (Blocked)

        This is the state when the thread is still alive, but is currently not eligible to run.

    5) Terminated

         A thread is in terminated or dead state when its run() method exits.
 
8).How to create the thread safe of objects and thread safe methods?


9).Runnable vs Callable?
ans:
      A Runnable object does not return a result whereas a Callable object returns a result.
      A Runnable object cannot throw a checked exception wheras a Callable object can throw an exception.
      The Runnable interface has been around since Java 1.0 whereas Callable was only introduced in Java 1.5.
       Few similarities include

     Instances of the classes that implement Runnable or Callable interfaces are potentially executed by another thread.
     Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.

10).What is the difference b/w Synchronized methods and Synchronized blocks?
  ans:
    Synchronized methode:
         If you declare any method as synchronized, it is known as synchronized method.

         Synchronized method is used to lock an object for any shared resource.

     Synchronized block:
         Synchronized block can be used to perform synchronization on any specific resource of the method.
         Synchronized block is used to lock an object for any shared resource.
         Scope of synchronized block is smaller than the method.



11).What is the use of "volatile",native and "synchronized" keywords?

 ans:
    volatile:
     
       volatile is a modifier applicable only variables,if a variable is declare as volatile then every thread a seperate local copy will be created

  synchronized:

       synchronized keword is apply to only blocks and method,
       if a method or block declare as a synchronized then at time only one thread is allowd to operate on the given object
       the main advantage is to reduce the data inconsistency problem
       the main disadvantage is increase the waiting time of thread effects the perfoamnce of the system

12).What is Serialization?Expalin with example.

     ans:Serialization in java is a mechanism of writing the state of an object into a byte stream.

         It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

          The reverse operation of serialization is called deserialization.
     ex:
        class Persist{
        public static void main(String args[])throws Exception{
            Student s1 =new Student(211,"ravi");
 
         FileOutputStream fout=new FileOutputStream("f.txt");
        ObjectOutputStream out=new ObjectOutputStream(fout);
 
        out.writeObject(s1);
       out.flush();
           System.out.println("success");
         }
         }


13).When we are using the serialization?

      ans:
       It is mainly used to travel object's state on the network (known as marshaling).


14).What is deserialization?Explain with example.
  ans:
     The reverse operation of serialization is called deserialization.
     ex;
         import java.io.*;
        class Depersist{
         public static void main(String args[])throws Exception{
   
         ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
           Student s=(Student)in.readObject();
          System.out.println(s.id+" "+s.name);
 
          in.close();
       }
       }
   


15).What is thread safety?Explain.
     Adding synchronized to this method will makes it thread-safe.
     When synchronized is added to a static method, the Class object is the object which is locked

     Synchronization is the easiest and most widely used tool for thread safety in java.

     Use of locks from java.util.concurrent.locks package.
     Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.
     Using volatile keyword with variables to make every thread read the data from memory, not read from thread cach
 


16).What is the difference b/w wait() and notify and notifyAll()?
   
     ans:
   1.wait()
     the wait() method is defined in object class
     wait() method release the lock

   
   2.notify()'
       notify() is used to unblock one thread
 

   3.notifyAll()
      notifyAll() is used to unblock  all the threads in waiting state


17).What is the difference b/w sleep() and wait() methods?

     1.sleep()
        The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
         sleep() method define in thread class
         sleep) method does not release the lock
   

     2.wait()
        the wait() method is defined in object class
        wait() method release the lock


18).What is the difference b/w sleep() and join() methods?
     1.sleep()
       The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

     2.join()
      The join() method waits for a thread to die. In other words,
      it causes the currently running threads to stop executing until the thread it joins with completes its task.


19).What is the difference b/w join() and yield() methods?
     1.join()
    The join() method waits for a thread to die. In other words,
      it causes the currently running threads to stop executing until the thread it joins with completes its task.


   2.yield()
       yield() method is used to puase the current excuting  thread for giving the chance to remaining waiting threads

20).How do you share the data b/w threads?(Interthread communication).
   
     ans:
     If two threads will communicate with each other by using wait() & notify(),notifyAll() is called  inter Therad Communication


21).What is the use of start() and run() methods?Explain.
     
      ans:
       start() methode:
            starts the execution of the thread.JVM calls the run() method on the thread.
 
       run methode:
           is used to perform action for a thread.


22).What is deadlock()?Explain.
    ans:
    if two threads are waiting for each other for ever such type of sittuation is called deadlock()



23).Explain locking concept in threads, and What is the difference b/w Object level lock and class level lock?


24).What is daemon thread?Give one example for daemon thread and How to create daemon thread?
   ans:
      Daemon thread in java is a service provider thread that provides services to the user thread.
       Its life depend on the mercy of user threads i.e. when all the user threads dies,
       JVM terminates this thread automatically.

     There are many java daemon threads running automatically e.g. gc, finalizer etc.

25).How to stop the thread in java?  
  ans:
     we can stop a thread excution in the middle by using stop() method.
     then the thread will be enter into dead state
 
     


26).What is thread priority?

    ans:
        Each thread have a priority. Priorities are represented by a number between 1 and 10.
         In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling).
         But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.


27).What is the use of transient keyword?
   ans:
 
   transient:
        transient is a keyword applicable only variables,at the time of serialization if we don't want save the value of a particular variable
         to meet security constraints then we should go for transient.
       at the time of serialization jvm ignore the original value of the transient variable and default value will be serializable

28).Difference b/w Serialization and Externalization?

    ans:
       Serialization in java is a mechanism of writing the state of an object into a byte stream.

         It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

          The reverse operation of serialization is called deserialization.

CTS PLSQL Interview Questions





1.      What are the environments in your company?

2.      How to know which version is currently running in your database?

SELECT * FROM V$VERSION
or
SELECT version FROM V$INSTANCE
or

BEGIN DBMS_OUTPUT.PUT_LINE(DBMS_DB_VERSION.VERSION || '.' || DBMS_DB_VERSION.RELEASE); END;


3.      Do you have any experience in data modeling?

4.      How to disable all triggers in a table? How many triggers are you created?

Alter table table_name disable all triggers;

5.      How many triggers created on one table?
12
6.      Which will fire default first statement level or row level trigger?
always constraint will fire first.

7.      What is bulk collect? And any restrictions in bulk collect? What is the use of limit clause in bulk collect?

8.      How to debugg your code?


9.      How to trace error handling?

10.  How to find which line error was raised?


11.  What are the methods there in save exceptions?

12.  What is functional based index? Write syntax?


13.  How to update complex view?

you can update complex view through 'instead of triggers' in oracle.

let take an example to update the view v1 (below) 

create or replace view v1 as
select  EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,dname
from emp e ,dept d where d.deptno = e.deptno

Instead of updating the view, you can create a trigger which overrides the default operation of 

the update statement: 

create or replace trigger update_emp_thru_v1_view
 instead of update on v1
 referencing new as new
 begin
     update emp 
      set ename = :new.ename,
      empno = :new.empno,
      job = :new.job,
      mgr = :new.mgr,
      hiredate = :new.hiredate,
      sal = :new.sal,
      comm = :new.comm,
      deptno = ( select deptno from dept where dname = :new.dname )
      where empno = :old.empno;
     if ( sql%rowcount = 0 )
       then
         raise_application_error
          ( -20001, 'Error updating the outemp view ...' );
     end if;

 end;

Then, you can update this from SQL*Plus as normally you do to a table ..

14.  Can you alter procedure with in package?
While the ALTER PACKAGE statement can be used to recompile the whole package, it
[...] does not change the declaration or definition of an existing package. To redeclare or redefine a package, use the CREATE PACKAGE or the CREATE PACKAGE BODY statement with the OR REPLACEclause.

15.  Is it possible to open cursor which is in package in another procedure?
YES

16.  What is substr()&instr()?
SUBSTR('This is a test', 6, 2)
Result: 'is'

SUBSTR('This is a test', 6)
Result: 'is a test'

SUBSTR('TechOnTheNet', 1, 4)
Result: 'Tech'

SUBSTR('TechOnTheNet', -3, 3)
Result: 'Net'

SUBSTR('TechOnTheNet', -6, 3)
Result: 'The'

SUBSTR('TechOnTheNet', -8, 2)
Result: 'On'

INSTR('Tech on the net', 'e')
Result: 2   (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 1)
Result: 2   (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 2)
Result: 11  (the second occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 3)
Result: 14  (the third occurrence of 'e')

INSTR('Tech on the net', 'e', -3, 2)
Result: 2

17.  Difference between case and decode?

18.  Can you use sysdate in check constraints? If no, why?

Oracle check constraint has some limitations. For one, subqueries cannot be usedwithin your Oracle check constraints. Also, an Oracle check constraint is able to reference another column. Sysdate, currval, nextval, level, rowid, uid, user or userenv cannot be referenced with Oracle check constraint.

19.  Difference between column level constraints & table level constraints?
a column level constraint has scope only to the column it is defined on. A table level constraint can see every column in the table. That is the major difference between the two - that of "scoping". Any column level constraint (exception: not null) can be expressed at the table level - but the opposite is not true

20.  What is optimizer?
The output from the optimizer is a plan that describes an optimum method of execution. The Oracle server provides the cost-based (CBO) and rule-based (RBO) optimization.

TCS PLSQL Interview Questions


1. What are the different types of joins?
Inner Join 
outer join (left outerjoin , right outer join)
full outer join
2. Explain normalization with examples.
First Normal Form : Avaoids relation within a relation
Second Normal Form : Fully functional depended on each key 
Third Normal Form : Avoids Transitivity dependency

3. What cursor type do you use to retrieve multiple recordsets?
 ref cursors'

4. State the difference between a "where" clause and a "having" clause
having comes along with group by

5. What is the difference between "procedure" and "function"?
procedure doesnot return a value thru return statement

6. How will you copy the structure of a table without copying the data?
select * from table_naem where 1 > 3

7. How to find out the database name from SQL*PLUS command prompt?
Select name from v$database

8. Tadeoffs with having indexes

9. Talk about "Exception Handling" in PL/SQL?

10. What is the difference between "NULL in C" and "NULL in Oracle?"

11. What is Pro*C? What is OCI?

12. Give some examples of Analytical functions.

13. What is the difference between "translate" and "replace"?

translate and replace both are replacing 3rd argument into first when 2nd argument is match with first.
but only difference is replace function replace whole string
but translate fucntion replace   character when matching  2nd argument with first.
syntax: translate(string, if , then)
                   
if condition matching

14. What is DYNAMIC SQL method 4?

SELECT ename, job, sal + comm FROM emp WHERE deptno = 20


15. How to remove duplicate records from a table?

SQL> DELETE FROM table_name A WHERE ROWID > (
  2    SELECT min(rowid) FROM table_name B
  3    WHERE A.key_values = B.key_values);
Delete all rowids that is BIGGER than the SMALLEST rowid value (for a given key).

Method 2:
SQL> create table table_name2 as select distinct * from table_name1;
SQL> drop table table_name1;
SQL> rename table_name2 to table_name1;


16. What is the use of Analyzing the tables?

Whenever we have some performance issues. First thing we will do is run this command on all the tables in our schema
so all the statistics are up to date.

ANALYZE TABLE <TABLE_NAME> COMPUTE STATISTICS;

We have Oracle 11g R2 database.


1) Is the command what we are using above is pretty old ? Is there a newer one ?
yes & yes

>
2) What command can we use as SYS user to ANALYZE an entire schema ?
DBMS_STATS.GATHER_SCHEMA_STATS

17. How to run SQL script from a Unix Shell?

18. What is a "transaction"? Why are they necessary?

19. Explain Normalization and Denormalization with examples.

20. When do you get constraint violation? What are the types of constraints?

21. How to convert RAW datatype into TEXT?

22. What is the difference between Primary Key and Aggregate Key

Primary Key is a much similar to unique key. Only difference is that unique key can be null but primary key can not be null. Primary key is used to avoid duplication of data.
A primary key consists of more than one column. Also known as a concatenated key or Aggregate Key. it is also called as composite key.
Example for varchar & varchar2()
Emp_name varchar(10) -  if you enter value less than 10 then remaining space can not be deleted. it used total 10 spaces.
Emp_name varchar2(10) - if you enter value less than 10 then remaining space is automatically deleted.

23. How functional dependency is related to database table design?

24. What is a "trigger"?

25. Why can a "group by" or "order by" clause be expensive to process?

26. What are "HINTS"? What is "index covering" of a query?

27. What is a VIEW? How to get script for a view?
View is a logical table based on a table or another view. logical in the sense it doesn't contains data of its own it a saved query in the database. 2 types are avialable simple view and complex view. The tables on which a view is based is called as base table. Views are saved as a select statement in the data dictionary user_views

28. What are the Large object types supported by Oracle?

29. What is SQL*Loader?
sql * loader is an enviornment where you are exucting sql and plsql statements.


30. Difference between "VARCHAR" and "VARCHAR2" datatypes.

The difference between Varchar and Varchar2 is both are variable length but only 2000 bytes of character of data can be store in varchar where as 4000 bytes of character of data can be store in varchar2.

31. What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table.

32. Difference between "ORACLE" and "MICROSOFT ACCESS" databases.
33. How to create a database link ?