Mysql interview questions and answers

Mysql interview questions and answers are below

Questions : 1     how to do login in mysql with unix shell
Answers :1     By below method if password is pass and user name is root
# [mysql dir]/bin/mysql -h hostname -u root -p pass
     
Questions : 2     how you will Create a database on the mysql server with unix shell
Answers : 2     mysql> create database databasename;
     
Questions : 3     how to list or view all databases from the mysql server.
Answers : 3     mysql> show databases;
     
Questions : 4     How Switch (select or use) to a database.
Answers : 4     mysql> use databasename;
     
Questions : 5     How To see all the tables from a database of mysql server.
Answers : 5     mysql> show tables;
     
Questions : 6     How to see table's field formats or description of table .
Answers : 6     mysql> describe tablename;
     
Questions : 7     How to delete a database from mysql server.
Answers : 7     mysql> drop database databasename;
     
Questions : 8     How we get Sum of column
Answers : 8     mysql> SELECT SUM(*) FROM [table name];
     
Questions : 9     How to delete a table
Answers : 9     mysql> drop table tablename;
     
Questions : 10     How you will Show all data from a table.
Answers : 10     mysql> SELECT * FROM tablename;
     
Questions : 11     How to returns the columns and column information pertaining to the designated table
Answers : 11     mysql> show columns from tablename;
     
Questions : 12     How to Show certain selected rows with the value "pcds"
Answers : 12     mysql> SELECT * FROM tablename WHERE fieldname = "pcds";
     
Questions : 13     How will Show all records containing the name "sonia" AND the phone number '9876543210'
Answers : 13     mysql> SELECT * FROM tablename WHERE name = "sonia" AND phone_number = '9876543210';
     
Questions : 14     How you will Show all records not containing the name "sonia" AND the phone number '9876543210' order by the phone_number field.
Answer : 14     mysql> SELECT * FROM tablename WHERE name != "sonia" AND phone_number = '9876543210' order by phone_number;
     
Questions : 15     How to Show all records starting with the letters 'sonia' AND the phone number '9876543210'
Answers : 15     mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = '9876543210';
     
Questions : 16     How to show all records starting with the letters 'sonia' AND the phone number '9876543210' limit to records 1 through 5.
Answers : 16     mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = '9876543210' limit 1,5;
     
Questions : 16     Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with r.
Answer : 16     mysql> SELECT * FROM tablename WHERE rec RLIKE "^r";
     
Questions : 17     How you will Show unique records.
Answer : 17     mysql> SELECT DISTINCT columnname FROM tablename;
     
Questions : 18     how we will Show selected records sorted in an ascending (asc) or descending (desc)
Answer : 18     mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;

mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC;

     
Questions : 19     how to Return total number of rows.
Answers : 19     mysql> SELECT COUNT(*) FROM tablename;
     
Questions : 20     How to Join tables on common columns.
Answer : 20     mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id
     
Questions : 21     How to Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
Answer : 21     # mysql -u root -p

mysql> use mysql;

mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));

mysql> flush privileges;
     
Questions : 22     How to Change a users password from unix shell.
Answers : 22     # [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
     
Questions : 23     How to Change a users password from MySQL prompt. Login as root. Set the password. Update privs.
Answer : 23     # mysql -u root -p

mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

mysql> flush privileges;
     
Questions : 24     How to Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.
Answer : 24     # /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
     
Questions : 25     How to Set a root password if there is on root password.
Answer : 25     # mysqladmin -u root password newpassword
     
Questions : 26     How to Update a root password.
Answer : 26     # mysqladmin -u root -p oldpassword newpassword
     
Questions : 27     How to allow the user "sonia" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.
Answers : 27     # mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to sonia@localhost identified by 'passwd';
mysql> flush privileges;
     
Questions : 28     How to give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.
Answers : 28     # mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
     
Questions : 29     How To update info already in a table and Delete a row(s) from a table.
Answer : 29     mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';
mysql> DELETE from [table name] where [field name] = 'whatever';
     
Questions : 30     How to Update database permissions/privilages.
Answer : 30     mysql> flush privileges;
     
Questions : 31     How to Delete a column and Add a new column to database
Answer : 31     mysql> alter table [table name] drop column [column name];
mysql> alter table [table name] add column [new column name] varchar (20);
     
Questions : 32     Change column name and Make a unique column so we get no dupes.
Answer : 32     mysql> alter table [table name] change [old column name] [new column name] varchar (50);
mysql> alter table [table name] add unique ([column name]);
     
Questions : 33     How to make a column bigger and Delete unique from table.
Answer : 33     mysql> alter table [table name] modify [column name] VARCHAR(3);
mysql> alter table [table name] drop index [colmn name];
     
Questions : 34     How to Load a CSV file into a table
Answer : 34     mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
     
Questions : 35     How to dump all databases for backup. Backup file is sql commands to recreate all db's.
Answer : 35     # [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
     
Questions : 36     How to dump one database for backup.
Answer : 36     # [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql
     
Questions : 37     How to dump a table from a database.
Answer : 37     # [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
     
Questions : 38     Restore database (or database table) from backup.
Answer : 38     # [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
     
Questions : 39     How to Create Table show Example
Answer : 39     mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Questions : 40     How to search second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load?
Answers : 40    

By below query we will get second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load?
SELECT DISTINCT(salary) FROM employee order by salary desc limit 1 , 1 ;
(This way we will able to find out 3rd highest , 4th highest salary so on just need to change limit condtion like LIMIT 2,1 for 3rd highest and LIMIT 3,1 for 4th
some one may finding this way useing below query that taken more time as compare to above query SELECT salary FROM employee where salary < (select max(salary) from employe) order by salary DESC limit 1 ;

OOPs interview questions and answers

Top OOPs interview questions and answers are below
Questions : 1     What is Object Oriented Programming ?
Answers : 1    

It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world concept. These objects have responsibilities and provide services to application or other objects.
     
Questions : 2     What is a Class ?
Answers : 2    

A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type which represents a blue print of objects. It’s a template of object.
     
Questions : 3     What is an Object ?
Answers : 3    

It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.
     
Questions : 4     What is the relation between Classes and Objects?
Answers : 4    

They look very much same but are not same. Class is a definition, while object is instance of the class created. Class is a blue print while objects are actual objects existing in real world. Example we have class CAR which has attributes and methods like Speed, Brakes, Type of Car etc.Class CAR is just a prototype, now we can create real time objects which can be used to provide functionality. Example we can create a Maruti car object with 100 km speed and urgent brakes.
     
Questions : 5     What are different properties provided by Object-oriented systems ?
Answers : 5    

Following are characteristics of Object Oriented System’s:-
Abstraction
It allows complex real world to be represented in simplified manner. Example color is abstracted to RGB.By just making the combination of these three colors we can achieve any color in world. It’s a model of real world or concept.
Encapsulation
The process of hiding all the internal details of an object from the outside world.
Communication
Using messages when application wants to achieve certain task it can only be done using combination of objects. A single object can not do the entire task. Example if we want to make order processing form. We will use Customer object, Order object, Product object and Payment object to achieve this functionality. In short these objects should communicate with each other. This is achieved when objects send messages to each other.
Object lifetime
All objects have life time. Objects are created, initialized, necessary functionalities are done and later the object is destroyed. Every object have there own state and identity, which differ from instance to instance.
     
Questions : 6     What is an Abstract class ?
Answers : 6    

Abstract class defines an abstract concept which can not be instantiated and comparing o interface it can have some implementation while interfaces can not. Below are some
points for abstract class:-
=>We can not create object of abstract class it can only be inherited in a below class.
=> Normally abstract classes have base implementation and then child classes derive from the abstract class to make the class concrete.
     
Questions : 7     What are Abstract methods?
Answers : 7    

Abstract class can contain abstract methods. Abstract methods do not have implementation. Abstract methods should be implemented in the subclasses which inherit them. So if an abstract class has an abstract method class inheriting the abstract class should implement the method or else java compiler will through an error. In this way, an abstract class can define a complete programming interface thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. Abstract methods are defined using "abstract" keyword. Below is a sample code snippet.
abstract class pcdsGraphics
{
abstract void draw();
}
Any class inheriting from "pcdsGraphics" class should implement the "draw" method or else the java compiler will throw an error. so if we do not implement a abstract method the program will not compile.
     
Questions : 8     What is the difference between Abstract classes and Interfaces ?
Answers : 8    

Difference between Abstract class and Interface is as follows:-
Abstract class can only be inherited while interfaces can not be it has to be implemented.
Interface cannot implement any methods, whereas an abstract class can have implementation.
Class can implement many interfaces but can have only one super class.
Interface is not part of the class hierarchy while Abstract class comes in through inheritance.
Unrelated classes can implement the same interface.
     
Questions : 9     What is difference between Static and Non-Static fields of a class ?
Answers : 9    

Non-Static values are also called as instance variables. Each object of the class has its own copy of Non-Static instance variables. So when a new object is created of the same class it will have completely its own copy of instance variables. While Static values have only one copy of instance variables and will be shared among all the objects of the class.
     
Questions : 10     What are inner classes and what is the practical implementation of inner classes?
Answers : 10    

Inner classes are nested inside other class. They have access to outer class fields and methods even if the fields of outer class are defined as private.
public class Pcds
{
class pcdsEmp
{
// inner class defines the required structure
String first;
String last;
}
// array of name objects
clsName personArray[] = {new clsName(), new clsName(), new clsName()};
}
Normally inner classes are used for data structures like one shown above or some kind of helper classes.
     
Questions : 11     What is a constructor in class?
Answers : 11    

Constructor has the same name as the class in which it resides and looks from syntax point of view it looks similiar to a method. Constructor is automatically called immediately after the object is created, before the new operator completes. Constructors have no return type, not even void. This is because the implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.
     
Questions : 12     Can constructors be parameterized?
Answers : 12    

Yes we can have parameterized constructor which can also be termed as constructor overloading. Below is a code snippet which shows two constructors for pcdsMaths class one with parameter and one with out.
class pcdsMaths
{
double PI;
// This is the constructor for the maths constant class.
pcdsMaths()
{PI = 3.14;}
pcdsMaths(int pi)
{
PI = pi;
} }
     
Questions : 13     What is the use if instanceof keyword? and How do refer to a current instance of object?
Answers : 13    

"instanceof" keyword is used to check what is the type of object.
we can refer the current instance of object using "this" keyword. For instance if we have class which has color property we can refer the current object instance inside any of the method using "this.color".
     
Questions : 14     what is Bootstrap, Extension and System Class loader? or Can you explain primordial class loader?
Answers : 14    

There three types of class loaders:-
BootStrap Class loader also called as primordial class loader.
Extension Class loader.
System Class loader. Let’s now try to get the fundamentals of these class loaders.

Bootstrap Class loader
Bootstrap class loader loads those classes those which are essential for JVM to function properly. Bootstrap class loader is responsible for loading all core java classes for instance java.lang.*, java.io.* etc. Bootstrap class loader finds these necessary classes from “jdk/ jre/lib/rt.jar”. Bootstrap class loader can not be instantiated from JAVA code and is implemented natively inside JVM.
Extension Class loader
The extension class loader also termed as the standard extensions class loader is a child of the bootstrap class loader. Its primary responsibility is to load classes from the extension directories, normally located the “jre/lib/ext” directory. This provides the ability to simply drop in new extensions, such as various security extensions, without requiring modification to the user's class path.
System Class loader
The system class loader also termed application class loader is the class loader responsible for loading code from the path specified by the CLASSPATH environment variable. It is also used to load an application’s entry point class that is the "static void main ()" method in a class.
     
Questions : 15     what’s the main difference between ArrayList / HashMap and Vector / Hashtable?
Answers : 15    

Vector / HashTable are synchronized which means they are thread safe. Cost of thread safe is performance degradation. So if you are sure that you are not dealing with huge number of threads then you should use ArrayList / HashMap.But yes you can still
synchronize List and Map’s using Collections provided methods :-
List OurList = Collections.synchronizedList (OurList);
Map OurMap = Collections.synchronizedMap (OurMap);
     
Questions : 16     What are access modifiers?
Answers : 16    

Access modifiers decide whether a method or a data variable can be accessed by another method in another class or subclass.
four types of access modifiers:
Public: - Can be accessed by any other class anywhere.
Protected: - Can be accessed by classes inside the package or by subclasses ( that means classes who inherit from this class).
Private - Can be accessed only within the class. Even methods in subclasses in the same package do not have access.
Default - (Its private access by default) accessible to classes in the same package but not by classes in other packages, even if these are subclasses.
     
Questions : 17     Define exceptions ?
Answers : 17    

An exception is an abnormal condition that arises in a code sequence at run time. Basically there are four important keywords which form the main pillars of exception handling: try, catch, throw and finally. Code which you want to monitor for exception is contained in the try block. If any exception occurs in the try block its sent to the catch block which can handle this error in a more rational manner. To throw an exception manually you need to call use the throw keyword. If you want to put any clean up code use the finally block. The finally block is executed irrespective if there is an error or not.
     
Questions : 18     What is serialization?How do we implement serialization actually?
Answers : 18    

Serialization is a process by which an object instance is converted in to stream of bytes. There are many useful stuff you can do when the object instance is converted in to stream of bytes for instance you can save the object in hard disk or send it across the network.

In order to implement serialization we need to use two classes from java.io package ObjectOutputStream and ObjectInputStream. ObjectOutputStream has a method called writeObject, while ObjectInputStream has a method called readObject. Using writeobject we can write and readObject can be used to read the object from the stream. Below are two code snippet which used the FileInputStream and FileOutputstream to read and write from harddisk.

DEAD LOCKS


In  multiprogramming environment, several processes  may  complete for  finite number of resources. A process requests resources,  and  if the resources are not available at that time, the process enters a wait state.  It  may happen that waiting processes will never  again  change state, because the resources that they have requested are held by other waiting processes. This situation is called a Deadlock.

For example, a system contains four tape drives and two processes. i.e.., each process holds two tape drives but needs three, then each  will wait for the other release its tape drives. This situation is a  "deadlock". The system resources are partitioned into several types, each of
which consist of some number of identical instances. If a  system  has two CPU's, then the resource type CPU has two instances. All  instances of  a resource type must be identical, if not the resource type  classes have to be properly defined. A process must request the resource before using it and release the resource after using it. A process may request as may resources as it requires, but the number of resources  requested may not exceed the total number of resources available in the system.  A process may utilize a resource only in the following sequence.

Request : if the request cannot be immediately granted,  then  the requesting process must wait until it can acquire the resources.

Use : the process can operate on the resource.

Release : the process release the resource.


DEADLOCK Definition : A  set of processes is in a deadlock state when every process  in the set is waiting an event that can only caused by another process  in the  set, consider a system with three tape drives. Suppose that  there are  three  processes, each holding one of these tape drives.  If  each process not requests another tape drive, the three processes will be in a  deadlock  state.  Each  is  waiting for  an  event  "tape  drive  is released", which can only caused by one of the other waiting processes.

DEADLOCK 2nd Definition :  A process request resources and if the resources are not available  at that  time,  the process enters a wait state. The  process  will  never change  state  because the resources they have  requested are  held  by after waiting process. This situation is known as DEADLOCK.

2. What are the necessary conditions for a DEADLOCK ?

A  deadlock  situation  can arise if and only if  the  following  four conditions hold simultaneously in a system.

1) Mutual Exclusion :  At  least one resource is help in a non-sharable mode, i.e., only  one process at a time can use the resource. If the another process requests that  resource,  the requesting process must be delayed until  the  resource has been released.

2) Hold and Wait : There  must exist a process that is holding at least one  resource  and i.e., waiting to acquire additional resources that are currently  being help be other processes.

3) No preemption : Resources  can  not be preempted; that is, a resource can  be  released only  voluntarily  by  the process holding it, after  the  process  has completed its task.

4) Circular wait :  There must exist a set { p0,p1.......pn) of waiting processes  such that p is waiting for a resource which is held by p is waiting for a  resource  which  is held by p1.p1 is waiting  for  a resource  which is held by p2……. Pn-1 is waiting for a resource  that  is held by pn. We emphasize  that  all four conditions must hold for  a  deadlock  to occur.

3. Explain Resource Allocation Graph (RAG).

Deadlocks can be described more precisely in terms of a directed  graph called a “(system) resource allocation graph".  This graph consists  of a pair G = (V1
,p2,p3,…..pn},  set of   all processes in the system, and R = {r1,r2,r3,......rn},  set of all resource types in the system.

Each element in the set E is an ordered pair (pi,rj) or (rj,pi),  where pi is a process and rj is a resource type.  If (pi,rj) belongs  to  E, then  there  is a directed edge from resource type rj  to process  pi implying  that  an instance of resource type r has been  allocated  to process  pi.  An edge (pi,rj) is called a request edge, while  an  edge(rj,pi ) is called an assignment edge. Pictorially, we  represent each process Pi as a circle  and  each resource type rj as a square. The instance can be represented by a  dot within  the  edge must also disignate one of the dots  in  the  square. Whenever  a process requests an instance of resource type,  an  request edge is inserted in the graph. When this request can be fulfilled,  the request edge is instance resource, the assignment edge is deleted.
 
Resource type r1 is having one instance, r2 is having two instances, r3 is having one instance and r4 is having three instances. Process  p1 is holding an instance of resource type r2 and  is  waiting for an instance of r1. Process p2 is holding an instance of r1 and is waiting for an instance of r3. Process p3 is holding an instance of r3.

 If  a graph contains no cycles, then no process in the system is  deadlocked. Otherwise a deadlock may exist.

4.  What are the methods for handling DEADLOCKS ?

There are two methods of ensuring that deadlocks never occur.

a) Deadlock prevention.
b) Deadlock avoidance.

5.  Explain DEADLOCK PREVENTION .

We know that, there are four necessary conditions must hold to occur  a dead  lock.  By ensuring that atleast one of  these  conditions  cannot hold. We can prevent the occurrence of a DEADLOCK. 

Mutual Exclusion :  If  all  the resources are sharable, then mutual  exclusion  will  not hold. Sharable resources do not require mutual exclusive  access,  and cannot be involved in a deadlock. But we can't put all resources in the sharable mode. for example A printer cannot be simultaneously shared by several processes. In general, it is not possible to prevent  deadlocks by denying the mutual exclusion condition.

Hold And Wait :    In order to ensure that the hold and wait condition never holds  in the system, we must guarantee that whenever a process requests  a  resource it does not hold any other resources.

   One  protocol that can be used requires each process to request  and be allocated all of its resources before it begins execution.

 An alternative protocol allows a process to request resources  only when  it has none. A process may request some resources and  use  them. Before it can request any additional resources, it must release all the resources that it is currently allocated.

   There are two main disadvantages to these protocols.

First one is , resource utilization may be very low, since many of  the resources may be allocated but unused for a long period. Second  one  is, starvation is possible. A process that needs  several popular resources may have to wait indefinitely because atleast one  of the resources that it needs is always allocated to some other process.  

No Preemption : To  ensure  that this condition does hold, the  following  protocol  is  If  a process is holding some resources requests another  resources that cannot be immediately allocated to it then all resources currently being held are preempted. The preempted resources are added to the list of  resources  for which the process is waiting. The process  will  not only be restarted when it can regain its old resources, as well as  the new ones that it is requesting.

   Alternatively, if a process requests some resources, we first  check whether they are available. If they are available, we allocate them. If they  are  not available, we check whether they are allocated  to  some other process  that is waiting for additional resources.  If   so,  we
preempt  the desired resources from the waiting process  and  allocate them to the requesting process. If the resources are not either  available  or help by a waiting process, the requesting process  must  wait. While it is waiting, some of its resources may be preempted, but  only if  another  process requests them. A process can be re  started.  Only when  it is allocated the new resources it is requesting  and  recovers any resources that were preempted while it was waiting.

Circular Wait : To  ensure  that this condition does not hold, each  resource  type  is assigned a unique integer number, which allows to compare two resources and determine whether one preceeds another in our ordering. Each  process can only request resources in an increasing order of enumeration.

Let R= { R1,R2,....Rn } be the set of resource types. We assign to each resource  a unique integer number, say  F: R - N, where N is the set  of natural numbers. For example set of resource types are tape drive, disk drive, printer, then the function F might defined as follows :

           F( tape drive ) = 1
                       F( disk drive ) = 5
           F( printer ) = 12

   We now consider the following protocol to prevent  deadlocks.  Each process  can request resources only in an increasing order of  enumeration. That is, a process can initially request any number of  instances of  a  resource type, say Ri. After that the process  can  request  instances of resource type Rj, if and only if F(Rj)>F(Ri).  If this protocol is used, the circular wait condition cannot  hold. We  can demonstrate this fact by assuming that a circular  wait  exists (proof by contradiction).

Let the set of processes in the circular wait be { P0,P1, ...Pn}.

P0  is  waiting  for a resource R0, which is held  by  P1.  Then according to our protocol F(R0)1
).

P1 is  waiting  for a resource R1, which is held  by  P2.  Then according to our protocol F(R1)2
).

P2 is  waiting  for a resource R2, which is held  by  P3.  Then according to our protocol F(R2)3
).

Pn-1 is  waiting for a resource Rn-1, which is held by  Pn.  Then according to our protocol F(Rn-1)n
).

Pn is waiting for a resource Rn, which is held by P0. Then according to our protocol F(Rn)0
).



This means that    F(R0) < F(R1) < .......< F(Rn) < F(R0) implies that  F(R0) < F(R0) which is impossible.

Therefore, there can be no circular wait.

6.   Explain DEADLOCK AVOIDANCE.
           
In  this method, it is necessary to obtain additional  information about how resources are to be requested. With the knowledge of complete sequence of requests and releases for each process, one can decide  for each  request  whether  or not the process should  wait.  Each  request requires  that the system consider the resources  currently  available, the  resources currently allocated to each process, and the future  re-quests  and releases of each process, to decide if the current  request can be satisfied or must wait to avoid a possible future deadlock.

   It is better to know the maximum number of resources of  each  type each  process needs. A deadlock avoidance algorithm dynamically  checks the resource allocation state (i.e., the number of available and  allocated resources, and the maximum demands of the processes)  to  ensure that  there can never be a circular wait condition. A state is safe  if the  system can allocate resources to each process (up to its  maximum) in  some order and still avoid a deadlock. A system is in a same  state only if there exists a safe sequence  of process is a safe  sequence  for the current allocation state if for  each p1, presources which p1 can still request can be satisfied by the  currently available resources plus the resources held by all the Pj, with j>i. If no such a sequence exists, then the system state is said to be unsafe.

    A safe state is not a deadlock state, and a deadlock state  is  an unsafe state. An unsafe state may lead to a deadlock.

 Several Instances Of A Resource Type : An algorithm, known as banker's algorithm, is used for deadlock  avoidance is as follows.

    When  a  process  enters the system, it must  declare  the  maximum number  of  instances  of each resource type that it  may  need.  This number  may not exceed of the total number of resources in the  system.  When a user requests a set of resources, it must be determined  whether the  allocation  of these allocated, otherwise, the process  must  wait until some other process releases enough resources. Let  n  be the number of processes in the system and m be  the   number   resource types.  The following data structures are needed.

Available : A vector of length 'm' indicating the number of  available resources of each type.  If Available [j] = k, there are 'k'  instances of resource type rj available.

Max : An n x m matrix defining the maximum demand of each process.  If Max[i,j]  =  k, then process p may request at most  'k'  instances  of resource type rj.

Allocation : An n x m matrix defining the number of resources of  each type currently allocated to each process.  If Allocation[i,j] = k, then process pi is currently allocated 'k' instances of resource type rj.

Need : An  n x m matrix indicating the remaining resource need of  each process.  If Need[i,j]= k, then process pi may need 'k' more instances of resource type rj, in order to complete its task.
Need[i,j] = Max[i,j] - Allocation[i,j].

             If  X  and Y are vectors of length n, then x <= y if and  only  if x[i]  <= y[i] for all i = 1,2...n.  For example, if  x =  (1,7,3,2) and y = (0,3,2,1) then Y <= x.

Each row of matrices Allocation and Need are treated as vectors Allocation  and Need respectively. Allocation specifies the resources  currently  allocated to process P, while Need specifies  the  additional resources  the  process P may still request in order to  complete  its importance.

Banker's Algorithm :

Let Request ti be the request vector for process Pi .

If Request ti [j] = k, then process Pi wants 'k' instances of resource type rj. When a request for resources is made by process Pi, the following steps are taken.

1.  If Request ti <= Need then proceed to step 2. Else an error  message occurs, since the process has exceeded its maximum claim.

2.  If  Request ti <= Available then proceed to step 3.  Else  the  resources are not available process Pi must wait.

3.     Available  = Available - Request .
      Allocation = Allocation + Request  
      Need = Need - Request .   

 If the resulting resource allocation state is safe, process P allocated resources. If the new state is unsafe, then P must wait  for Request and the old resource allocation state is restored. This  Banker's Algorithm require m x n operations.

Safety Algorithm :    This algorithm finds out whether a system is in safe state or not.

1. Let  Work and Finish be vectors of length m and n respectively.
   Work = Available
   Finish [i] = False for i = 1,2,3, ...., n.

            2. Find an 'i' such that :
(i) Finish[i] = false, and
(ii) Need <= Work.
      If no such 'i' exists, go to step 4. 

3. work := work+allocation I finish[i]:=true , go to step2.

4. If  Finish[i] = true for all i, then the system is in a safe state.

 Single Instance Of Each Resource Type :  If  we have a resource allocation system with only one  instance  of each resource type, a more efficient algorithm can be defined. In  this algorithm, in addition to the request and assignement edges of a  resource allocation graph, a claim edge is introduced. A claim edge (pi,rj) indicated that process Pi may request resource r in future. This edge is indicated by a dashed line and resembles the direction  of a request edge. When process Pi requests resource rj, then this  claim  edge  is converted to a request edge. When a resource is released,  the assignement edge is converged to a claim edge. Before process Pi starts executing  all of its claim edges must already appear in  the  resource allocation graph. A requesting edge is converted to an assignment  edge only  if this assignment does not result lin the formation of cycle  in the  resource allocation  graph. If a cycle is found, then  process  Pi must  wait for its requests in order not to enter in an  unsafe  state.

For example, in the following allocation graph, p2 requests r2. Even if  is currently free, we cannot allocate it to P2 since this allocation will  create a cycle in the graph. If Pi requests rj, a  deadlock  will occur.
 

Friday 5 October 2012

Mysql interview questions and answers

Mysql interview questions and answers are below

Questions : 1     how to do login in mysql with unix shell
Answers :1     By below method if password is pass and user name is root
# [mysql dir]/bin/mysql -h hostname -u root -p pass
     
Questions : 2     how you will Create a database on the mysql server with unix shell
Answers : 2     mysql> create database databasename;
     
Questions : 3     how to list or view all databases from the mysql server.
Answers : 3     mysql> show databases;
     
Questions : 4     How Switch (select or use) to a database.
Answers : 4     mysql> use databasename;
     
Questions : 5     How To see all the tables from a database of mysql server.
Answers : 5     mysql> show tables;
     
Questions : 6     How to see table's field formats or description of table .
Answers : 6     mysql> describe tablename;
     
Questions : 7     How to delete a database from mysql server.
Answers : 7     mysql> drop database databasename;
     
Questions : 8     How we get Sum of column
Answers : 8     mysql> SELECT SUM(*) FROM [table name];
     
Questions : 9     How to delete a table
Answers : 9     mysql> drop table tablename;
     
Questions : 10     How you will Show all data from a table.
Answers : 10     mysql> SELECT * FROM tablename;
     
Questions : 11     How to returns the columns and column information pertaining to the designated table
Answers : 11     mysql> show columns from tablename;
     
Questions : 12     How to Show certain selected rows with the value "pcds"
Answers : 12     mysql> SELECT * FROM tablename WHERE fieldname = "pcds";
     
Questions : 13     How will Show all records containing the name "sonia" AND the phone number '9876543210'
Answers : 13     mysql> SELECT * FROM tablename WHERE name = "sonia" AND phone_number = '9876543210';
     
Questions : 14     How you will Show all records not containing the name "sonia" AND the phone number '9876543210' order by the phone_number field.
Answer : 14     mysql> SELECT * FROM tablename WHERE name != "sonia" AND phone_number = '9876543210' order by phone_number;
     
Questions : 15     How to Show all records starting with the letters 'sonia' AND the phone number '9876543210'
Answers : 15     mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = '9876543210';
     
Questions : 16     How to show all records starting with the letters 'sonia' AND the phone number '9876543210' limit to records 1 through 5.
Answers : 16     mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = '9876543210' limit 1,5;
     
Questions : 16     Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with r.
Answer : 16     mysql> SELECT * FROM tablename WHERE rec RLIKE "^r";
     
Questions : 17     How you will Show unique records.
Answer : 17     mysql> SELECT DISTINCT columnname FROM tablename;
     
Questions : 18     how we will Show selected records sorted in an ascending (asc) or descending (desc)
Answer : 18     mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;

mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC;

     
Questions : 19     how to Return total number of rows.
Answers : 19     mysql> SELECT COUNT(*) FROM tablename;
     
Questions : 20     How to Join tables on common columns.
Answer : 20     mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id
     
Questions : 21     How to Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
Answer : 21     # mysql -u root -p

mysql> use mysql;

mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));

mysql> flush privileges;
     
Questions : 22     How to Change a users password from unix shell.
Answers : 22     # [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
     
Questions : 23     How to Change a users password from MySQL prompt. Login as root. Set the password. Update privs.
Answer : 23     # mysql -u root -p

mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

mysql> flush privileges;
     
Questions : 24     How to Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.
Answer : 24     # /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
     
Questions : 25     How to Set a root password if there is on root password.
Answer : 25     # mysqladmin -u root password newpassword
     
Questions : 26     How to Update a root password.
Answer : 26     # mysqladmin -u root -p oldpassword newpassword
     
Questions : 27     How to allow the user "sonia" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.
Answers : 27     # mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to sonia@localhost identified by 'passwd';
mysql> flush privileges;
     
Questions : 28     How to give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.
Answers : 28     # mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
     
Questions : 29     How To update info already in a table and Delete a row(s) from a table.
Answer : 29     mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';
mysql> DELETE from [table name] where [field name] = 'whatever';
     
Questions : 30     How to Update database permissions/privilages.
Answer : 30     mysql> flush privileges;
     
Questions : 31     How to Delete a column and Add a new column to database
Answer : 31     mysql> alter table [table name] drop column [column name];
mysql> alter table [table name] add column [new column name] varchar (20);
     
Questions : 32     Change column name and Make a unique column so we get no dupes.
Answer : 32     mysql> alter table [table name] change [old column name] [new column name] varchar (50);
mysql> alter table [table name] add unique ([column name]);
     
Questions : 33     How to make a column bigger and Delete unique from table.
Answer : 33     mysql> alter table [table name] modify [column name] VARCHAR(3);
mysql> alter table [table name] drop index [colmn name];
     
Questions : 34     How to Load a CSV file into a table
Answer : 34     mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
     
Questions : 35     How to dump all databases for backup. Backup file is sql commands to recreate all db's.
Answer : 35     # [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
     
Questions : 36     How to dump one database for backup.
Answer : 36     # [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql
     
Questions : 37     How to dump a table from a database.
Answer : 37     # [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
     
Questions : 38     Restore database (or database table) from backup.
Answer : 38     # [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
     
Questions : 39     How to Create Table show Example
Answer : 39     mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Questions : 40     How to search second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load?
Answers : 40    

By below query we will get second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load?
SELECT DISTINCT(salary) FROM employee order by salary desc limit 1 , 1 ;
(This way we will able to find out 3rd highest , 4th highest salary so on just need to change limit condtion like LIMIT 2,1 for 3rd highest and LIMIT 3,1 for 4th
some one may finding this way useing below query that taken more time as compare to above query SELECT salary FROM employee where salary < (select max(salary) from employe) order by salary DESC limit 1 ;

OOPs interview questions and answers

Top OOPs interview questions and answers are below
Questions : 1     What is Object Oriented Programming ?
Answers : 1    

It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world concept. These objects have responsibilities and provide services to application or other objects.
     
Questions : 2     What is a Class ?
Answers : 2    

A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type which represents a blue print of objects. It’s a template of object.
     
Questions : 3     What is an Object ?
Answers : 3    

It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.
     
Questions : 4     What is the relation between Classes and Objects?
Answers : 4    

They look very much same but are not same. Class is a definition, while object is instance of the class created. Class is a blue print while objects are actual objects existing in real world. Example we have class CAR which has attributes and methods like Speed, Brakes, Type of Car etc.Class CAR is just a prototype, now we can create real time objects which can be used to provide functionality. Example we can create a Maruti car object with 100 km speed and urgent brakes.
     
Questions : 5     What are different properties provided by Object-oriented systems ?
Answers : 5    

Following are characteristics of Object Oriented System’s:-
Abstraction
It allows complex real world to be represented in simplified manner. Example color is abstracted to RGB.By just making the combination of these three colors we can achieve any color in world. It’s a model of real world or concept.
Encapsulation
The process of hiding all the internal details of an object from the outside world.
Communication
Using messages when application wants to achieve certain task it can only be done using combination of objects. A single object can not do the entire task. Example if we want to make order processing form. We will use Customer object, Order object, Product object and Payment object to achieve this functionality. In short these objects should communicate with each other. This is achieved when objects send messages to each other.
Object lifetime
All objects have life time. Objects are created, initialized, necessary functionalities are done and later the object is destroyed. Every object have there own state and identity, which differ from instance to instance.
     
Questions : 6     What is an Abstract class ?
Answers : 6    

Abstract class defines an abstract concept which can not be instantiated and comparing o interface it can have some implementation while interfaces can not. Below are some
points for abstract class:-
=>We can not create object of abstract class it can only be inherited in a below class.
=> Normally abstract classes have base implementation and then child classes derive from the abstract class to make the class concrete.
     
Questions : 7     What are Abstract methods?
Answers : 7    

Abstract class can contain abstract methods. Abstract methods do not have implementation. Abstract methods should be implemented in the subclasses which inherit them. So if an abstract class has an abstract method class inheriting the abstract class should implement the method or else java compiler will through an error. In this way, an abstract class can define a complete programming interface thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. Abstract methods are defined using "abstract" keyword. Below is a sample code snippet.
abstract class pcdsGraphics
{
abstract void draw();
}
Any class inheriting from "pcdsGraphics" class should implement the "draw" method or else the java compiler will throw an error. so if we do not implement a abstract method the program will not compile.
     
Questions : 8     What is the difference between Abstract classes and Interfaces ?
Answers : 8    

Difference between Abstract class and Interface is as follows:-
Abstract class can only be inherited while interfaces can not be it has to be implemented.
Interface cannot implement any methods, whereas an abstract class can have implementation.
Class can implement many interfaces but can have only one super class.
Interface is not part of the class hierarchy while Abstract class comes in through inheritance.
Unrelated classes can implement the same interface.
     
Questions : 9     What is difference between Static and Non-Static fields of a class ?
Answers : 9    

Non-Static values are also called as instance variables. Each object of the class has its own copy of Non-Static instance variables. So when a new object is created of the same class it will have completely its own copy of instance variables. While Static values have only one copy of instance variables and will be shared among all the objects of the class.
     
Questions : 10     What are inner classes and what is the practical implementation of inner classes?
Answers : 10    

Inner classes are nested inside other class. They have access to outer class fields and methods even if the fields of outer class are defined as private.
public class Pcds
{
class pcdsEmp
{
// inner class defines the required structure
String first;
String last;
}
// array of name objects
clsName personArray[] = {new clsName(), new clsName(), new clsName()};
}
Normally inner classes are used for data structures like one shown above or some kind of helper classes.
     
Questions : 11     What is a constructor in class?
Answers : 11    

Constructor has the same name as the class in which it resides and looks from syntax point of view it looks similiar to a method. Constructor is automatically called immediately after the object is created, before the new operator completes. Constructors have no return type, not even void. This is because the implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.
     
Questions : 12     Can constructors be parameterized?
Answers : 12    

Yes we can have parameterized constructor which can also be termed as constructor overloading. Below is a code snippet which shows two constructors for pcdsMaths class one with parameter and one with out.
class pcdsMaths
{
double PI;
// This is the constructor for the maths constant class.
pcdsMaths()
{PI = 3.14;}
pcdsMaths(int pi)
{
PI = pi;
} }
     
Questions : 13     What is the use if instanceof keyword? and How do refer to a current instance of object?
Answers : 13    

"instanceof" keyword is used to check what is the type of object.
we can refer the current instance of object using "this" keyword. For instance if we have class which has color property we can refer the current object instance inside any of the method using "this.color".
     
Questions : 14     what is Bootstrap, Extension and System Class loader? or Can you explain primordial class loader?
Answers : 14    

There three types of class loaders:-
BootStrap Class loader also called as primordial class loader.
Extension Class loader.
System Class loader. Let’s now try to get the fundamentals of these class loaders.

Bootstrap Class loader
Bootstrap class loader loads those classes those which are essential for JVM to function properly. Bootstrap class loader is responsible for loading all core java classes for instance java.lang.*, java.io.* etc. Bootstrap class loader finds these necessary classes from “jdk/ jre/lib/rt.jar”. Bootstrap class loader can not be instantiated from JAVA code and is implemented natively inside JVM.
Extension Class loader
The extension class loader also termed as the standard extensions class loader is a child of the bootstrap class loader. Its primary responsibility is to load classes from the extension directories, normally located the “jre/lib/ext” directory. This provides the ability to simply drop in new extensions, such as various security extensions, without requiring modification to the user's class path.
System Class loader
The system class loader also termed application class loader is the class loader responsible for loading code from the path specified by the CLASSPATH environment variable. It is also used to load an application’s entry point class that is the "static void main ()" method in a class.
     
Questions : 15     what’s the main difference between ArrayList / HashMap and Vector / Hashtable?
Answers : 15    

Vector / HashTable are synchronized which means they are thread safe. Cost of thread safe is performance degradation. So if you are sure that you are not dealing with huge number of threads then you should use ArrayList / HashMap.But yes you can still
synchronize List and Map’s using Collections provided methods :-
List OurList = Collections.synchronizedList (OurList);
Map OurMap = Collections.synchronizedMap (OurMap);
     
Questions : 16     What are access modifiers?
Answers : 16    

Access modifiers decide whether a method or a data variable can be accessed by another method in another class or subclass.
four types of access modifiers:
Public: - Can be accessed by any other class anywhere.
Protected: - Can be accessed by classes inside the package or by subclasses ( that means classes who inherit from this class).
Private - Can be accessed only within the class. Even methods in subclasses in the same package do not have access.
Default - (Its private access by default) accessible to classes in the same package but not by classes in other packages, even if these are subclasses.
     
Questions : 17     Define exceptions ?
Answers : 17    

An exception is an abnormal condition that arises in a code sequence at run time. Basically there are four important keywords which form the main pillars of exception handling: try, catch, throw and finally. Code which you want to monitor for exception is contained in the try block. If any exception occurs in the try block its sent to the catch block which can handle this error in a more rational manner. To throw an exception manually you need to call use the throw keyword. If you want to put any clean up code use the finally block. The finally block is executed irrespective if there is an error or not.
     
Questions : 18     What is serialization?How do we implement serialization actually?
Answers : 18    

Serialization is a process by which an object instance is converted in to stream of bytes. There are many useful stuff you can do when the object instance is converted in to stream of bytes for instance you can save the object in hard disk or send it across the network.

In order to implement serialization we need to use two classes from java.io package ObjectOutputStream and ObjectInputStream. ObjectOutputStream has a method called writeObject, while ObjectInputStream has a method called readObject. Using writeobject we can write and readObject can be used to read the object from the stream. Below are two code snippet which used the FileInputStream and FileOutputstream to read and write from harddisk.

Monday 1 October 2012

DEAD LOCKS


In  multiprogramming environment, several processes  may  complete for  finite number of resources. A process requests resources,  and  if the resources are not available at that time, the process enters a wait state.  It  may happen that waiting processes will never  again  change state, because the resources that they have requested are held by other waiting processes. This situation is called a Deadlock.

For example, a system contains four tape drives and two processes. i.e.., each process holds two tape drives but needs three, then each  will wait for the other release its tape drives. This situation is a  "deadlock". The system resources are partitioned into several types, each of
which consist of some number of identical instances. If a  system  has two CPU's, then the resource type CPU has two instances. All  instances of  a resource type must be identical, if not the resource type  classes have to be properly defined. A process must request the resource before using it and release the resource after using it. A process may request as may resources as it requires, but the number of resources  requested may not exceed the total number of resources available in the system.  A process may utilize a resource only in the following sequence.

Request : if the request cannot be immediately granted,  then  the requesting process must wait until it can acquire the resources.

Use : the process can operate on the resource.

Release : the process release the resource.


DEADLOCK Definition : A  set of processes is in a deadlock state when every process  in the set is waiting an event that can only caused by another process  in the  set, consider a system with three tape drives. Suppose that  there are  three  processes, each holding one of these tape drives.  If  each process not requests another tape drive, the three processes will be in a  deadlock  state.  Each  is  waiting for  an  event  "tape  drive  is released", which can only caused by one of the other waiting processes.

DEADLOCK 2nd Definition :  A process request resources and if the resources are not available  at that  time,  the process enters a wait state. The  process  will  never change  state  because the resources they have  requested are  held  by after waiting process. This situation is known as DEADLOCK.

2. What are the necessary conditions for a DEADLOCK ?

A  deadlock  situation  can arise if and only if  the  following  four conditions hold simultaneously in a system.

1) Mutual Exclusion :  At  least one resource is help in a non-sharable mode, i.e., only  one process at a time can use the resource. If the another process requests that  resource,  the requesting process must be delayed until  the  resource has been released.

2) Hold and Wait : There  must exist a process that is holding at least one  resource  and i.e., waiting to acquire additional resources that are currently  being help be other processes.

3) No preemption : Resources  can  not be preempted; that is, a resource can  be  released only  voluntarily  by  the process holding it, after  the  process  has completed its task.

4) Circular wait :  There must exist a set { p0,p1.......pn) of waiting processes  such that p is waiting for a resource which is held by p is waiting for a  resource  which  is held by p1.p1 is waiting  for  a resource  which is held by p2……. Pn-1 is waiting for a resource  that  is held by pn. We emphasize  that  all four conditions must hold for  a  deadlock  to occur.

3. Explain Resource Allocation Graph (RAG).

Deadlocks can be described more precisely in terms of a directed  graph called a “(system) resource allocation graph".  This graph consists  of a pair G = (V1
,p2,p3,…..pn},  set of   all processes in the system, and R = {r1,r2,r3,......rn},  set of all resource types in the system.

Each element in the set E is an ordered pair (pi,rj) or (rj,pi),  where pi is a process and rj is a resource type.  If (pi,rj) belongs  to  E, then  there  is a directed edge from resource type rj  to process  pi implying  that  an instance of resource type r has been  allocated  to process  pi.  An edge (pi,rj) is called a request edge, while  an  edge(rj,pi ) is called an assignment edge. Pictorially, we  represent each process Pi as a circle  and  each resource type rj as a square. The instance can be represented by a  dot within  the  edge must also disignate one of the dots  in  the  square. Whenever  a process requests an instance of resource type,  an  request edge is inserted in the graph. When this request can be fulfilled,  the request edge is instance resource, the assignment edge is deleted.
 
Resource type r1 is having one instance, r2 is having two instances, r3 is having one instance and r4 is having three instances. Process  p1 is holding an instance of resource type r2 and  is  waiting for an instance of r1. Process p2 is holding an instance of r1 and is waiting for an instance of r3. Process p3 is holding an instance of r3.

 If  a graph contains no cycles, then no process in the system is  deadlocked. Otherwise a deadlock may exist.

4.  What are the methods for handling DEADLOCKS ?

There are two methods of ensuring that deadlocks never occur.

a) Deadlock prevention.
b) Deadlock avoidance.

5.  Explain DEADLOCK PREVENTION .

We know that, there are four necessary conditions must hold to occur  a dead  lock.  By ensuring that atleast one of  these  conditions  cannot hold. We can prevent the occurrence of a DEADLOCK. 

Mutual Exclusion :  If  all  the resources are sharable, then mutual  exclusion  will  not hold. Sharable resources do not require mutual exclusive  access,  and cannot be involved in a deadlock. But we can't put all resources in the sharable mode. for example A printer cannot be simultaneously shared by several processes. In general, it is not possible to prevent  deadlocks by denying the mutual exclusion condition.

Hold And Wait :    In order to ensure that the hold and wait condition never holds  in the system, we must guarantee that whenever a process requests  a  resource it does not hold any other resources.

   One  protocol that can be used requires each process to request  and be allocated all of its resources before it begins execution.

 An alternative protocol allows a process to request resources  only when  it has none. A process may request some resources and  use  them. Before it can request any additional resources, it must release all the resources that it is currently allocated.

   There are two main disadvantages to these protocols.

First one is , resource utilization may be very low, since many of  the resources may be allocated but unused for a long period. Second  one  is, starvation is possible. A process that needs  several popular resources may have to wait indefinitely because atleast one  of the resources that it needs is always allocated to some other process.  

No Preemption : To  ensure  that this condition does hold, the  following  protocol  is  If  a process is holding some resources requests another  resources that cannot be immediately allocated to it then all resources currently being held are preempted. The preempted resources are added to the list of  resources  for which the process is waiting. The process  will  not only be restarted when it can regain its old resources, as well as  the new ones that it is requesting.

   Alternatively, if a process requests some resources, we first  check whether they are available. If they are available, we allocate them. If they  are  not available, we check whether they are allocated  to  some other process  that is waiting for additional resources.  If   so,  we
preempt  the desired resources from the waiting process  and  allocate them to the requesting process. If the resources are not either  available  or help by a waiting process, the requesting process  must  wait. While it is waiting, some of its resources may be preempted, but  only if  another  process requests them. A process can be re  started.  Only when  it is allocated the new resources it is requesting  and  recovers any resources that were preempted while it was waiting.

Circular Wait : To  ensure  that this condition does not hold, each  resource  type  is assigned a unique integer number, which allows to compare two resources and determine whether one preceeds another in our ordering. Each  process can only request resources in an increasing order of enumeration.

Let R= { R1,R2,....Rn } be the set of resource types. We assign to each resource  a unique integer number, say  F: R - N, where N is the set  of natural numbers. For example set of resource types are tape drive, disk drive, printer, then the function F might defined as follows :

           F( tape drive ) = 1
                       F( disk drive ) = 5
           F( printer ) = 12

   We now consider the following protocol to prevent  deadlocks.  Each process  can request resources only in an increasing order of  enumeration. That is, a process can initially request any number of  instances of  a  resource type, say Ri. After that the process  can  request  instances of resource type Rj, if and only if F(Rj)>F(Ri).  If this protocol is used, the circular wait condition cannot  hold. We  can demonstrate this fact by assuming that a circular  wait  exists (proof by contradiction).

Let the set of processes in the circular wait be { P0,P1, ...Pn}.

P0  is  waiting  for a resource R0, which is held  by  P1.  Then according to our protocol F(R0)1
).

P1 is  waiting  for a resource R1, which is held  by  P2.  Then according to our protocol F(R1)2
).

P2 is  waiting  for a resource R2, which is held  by  P3.  Then according to our protocol F(R2)3
).

Pn-1 is  waiting for a resource Rn-1, which is held by  Pn.  Then according to our protocol F(Rn-1)n
).

Pn is waiting for a resource Rn, which is held by P0. Then according to our protocol F(Rn)0
).



This means that    F(R0) < F(R1) < .......< F(Rn) < F(R0) implies that  F(R0) < F(R0) which is impossible.

Therefore, there can be no circular wait.

6.   Explain DEADLOCK AVOIDANCE.
           
In  this method, it is necessary to obtain additional  information about how resources are to be requested. With the knowledge of complete sequence of requests and releases for each process, one can decide  for each  request  whether  or not the process should  wait.  Each  request requires  that the system consider the resources  currently  available, the  resources currently allocated to each process, and the future  re-quests  and releases of each process, to decide if the current  request can be satisfied or must wait to avoid a possible future deadlock.

   It is better to know the maximum number of resources of  each  type each  process needs. A deadlock avoidance algorithm dynamically  checks the resource allocation state (i.e., the number of available and  allocated resources, and the maximum demands of the processes)  to  ensure that  there can never be a circular wait condition. A state is safe  if the  system can allocate resources to each process (up to its  maximum) in  some order and still avoid a deadlock. A system is in a same  state only if there exists a safe sequence  of process is a safe  sequence  for the current allocation state if for  each p1, presources which p1 can still request can be satisfied by the  currently available resources plus the resources held by all the Pj, with j>i. If no such a sequence exists, then the system state is said to be unsafe.

    A safe state is not a deadlock state, and a deadlock state  is  an unsafe state. An unsafe state may lead to a deadlock.

 Several Instances Of A Resource Type : An algorithm, known as banker's algorithm, is used for deadlock  avoidance is as follows.

    When  a  process  enters the system, it must  declare  the  maximum number  of  instances  of each resource type that it  may  need.  This number  may not exceed of the total number of resources in the  system.  When a user requests a set of resources, it must be determined  whether the  allocation  of these allocated, otherwise, the process  must  wait until some other process releases enough resources. Let  n  be the number of processes in the system and m be  the   number   resource types.  The following data structures are needed.

Available : A vector of length 'm' indicating the number of  available resources of each type.  If Available [j] = k, there are 'k'  instances of resource type rj available.

Max : An n x m matrix defining the maximum demand of each process.  If Max[i,j]  =  k, then process p may request at most  'k'  instances  of resource type rj.

Allocation : An n x m matrix defining the number of resources of  each type currently allocated to each process.  If Allocation[i,j] = k, then process pi is currently allocated 'k' instances of resource type rj.

Need : An  n x m matrix indicating the remaining resource need of  each process.  If Need[i,j]= k, then process pi may need 'k' more instances of resource type rj, in order to complete its task.
Need[i,j] = Max[i,j] - Allocation[i,j].

             If  X  and Y are vectors of length n, then x <= y if and  only  if x[i]  <= y[i] for all i = 1,2...n.  For example, if  x =  (1,7,3,2) and y = (0,3,2,1) then Y <= x.

Each row of matrices Allocation and Need are treated as vectors Allocation  and Need respectively. Allocation specifies the resources  currently  allocated to process P, while Need specifies  the  additional resources  the  process P may still request in order to  complete  its importance.

Banker's Algorithm :

Let Request ti be the request vector for process Pi .

If Request ti [j] = k, then process Pi wants 'k' instances of resource type rj. When a request for resources is made by process Pi, the following steps are taken.

1.  If Request ti <= Need then proceed to step 2. Else an error  message occurs, since the process has exceeded its maximum claim.

2.  If  Request ti <= Available then proceed to step 3.  Else  the  resources are not available process Pi must wait.

3.     Available  = Available - Request .
      Allocation = Allocation + Request  
      Need = Need - Request .   

 If the resulting resource allocation state is safe, process P allocated resources. If the new state is unsafe, then P must wait  for Request and the old resource allocation state is restored. This  Banker's Algorithm require m x n operations.

Safety Algorithm :    This algorithm finds out whether a system is in safe state or not.

1. Let  Work and Finish be vectors of length m and n respectively.
   Work = Available
   Finish [i] = False for i = 1,2,3, ...., n.

            2. Find an 'i' such that :
(i) Finish[i] = false, and
(ii) Need <= Work.
      If no such 'i' exists, go to step 4. 

3. work := work+allocation I finish[i]:=true , go to step2.

4. If  Finish[i] = true for all i, then the system is in a safe state.

 Single Instance Of Each Resource Type :  If  we have a resource allocation system with only one  instance  of each resource type, a more efficient algorithm can be defined. In  this algorithm, in addition to the request and assignement edges of a  resource allocation graph, a claim edge is introduced. A claim edge (pi,rj) indicated that process Pi may request resource r in future. This edge is indicated by a dashed line and resembles the direction  of a request edge. When process Pi requests resource rj, then this  claim  edge  is converted to a request edge. When a resource is released,  the assignement edge is converged to a claim edge. Before process Pi starts executing  all of its claim edges must already appear in  the  resource allocation graph. A requesting edge is converted to an assignment  edge only  if this assignment does not result lin the formation of cycle  in the  resource allocation  graph. If a cycle is found, then  process  Pi must  wait for its requests in order not to enter in an  unsafe  state.

For example, in the following allocation graph, p2 requests r2. Even if  is currently free, we cannot allocate it to P2 since this allocation will  create a cycle in the graph. If Pi requests rj, a  deadlock  will occur.