Monday, October 17, 2011

Example of Deadlock in Threads

Often we hear of Deadlocks. I tried replicating it using a simple example through threads.
Lets take an example of two people Jack and Jill; trying to exchange business cards.

Rules of exchanging cards
  1. You offer your business card to someone.
  2. The other person accepts your card and gives you his card.


DeadLock

What if both people offer each other cards at the same time? Since both have to follow the rules of exchanging cards, both of them will be stuck in a deadlock since both will wait for the other to accept their cards. (Ignore the case where they offer the card with one hand and accept it with other. Assume that both are one handed)





Java Code to Replicate the Above :
 
 
 
 
Output
Jack : I am giving card to Jill
Jill : I am giving card to Jack

Output if we uncomment the Thread.sleep try block in the code above
Jack : I am giving card to Jill
               Thankyou for your card.Please Accept My Card. My Name is :Jill
Jill : I am giving card to Jack
               Thankyou for your card.Please Accept My Card. My Name is :Jack
    

Thursday, June 23, 2011

JDBC for SQL Server

A quick copy paste code for connecting with SQL Server and executing a select statement or a Stored Procedure.

1. Imports :
 import java.sql.*;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.Statement;

 You will need sqljdbc4.jar in your classpath.

2. Code :
 try

 {
    DriverManager.registerDriver (new com.microsoft.sqlserver.jdbc.SQLServerDriver());
    Connection conespacxo = null;
    
    String connectionUrl = new String();
    ConnectionUrl="jdbc:sqlserver://?.?.?.?:1433;databaseName=??;user=prabhjot;password=lamba;";
    conespacxo = DriverManager.getConnection(connectionUrl);
    conespacxo.setAutoCommit(false);
        
    /*
      // Executing a select statement
     String selectString = "select distinct name from StudentDatabase";
     Statement stmt = conespacxo.createStatement();
     ResultSet rs1 = stmt.executeQuery(selectString);
     while (rs1.next())
     {
         String prodName = rs1.getString("name");
         System.out.println(prodName);
     }
     rs1.close();
     stmt.close();
     conespacxo.close();
*/

// Executing a Stored Procedure
CallableStatement call_stmt = conespacxo.prepareCall("{ call myStoredProcedure (?,?,?,?) }");
call_stmt.setString(1, "2011-06-01"); // From Date
call_stmt.setString(2, "2011-06-20"); // To Date
call_stmt.setString(3, "SharePrice"); // What to Get
call_stmt.setString(4, "Google"); // Company Name
   
ResultSet rs = call_stmt.executeQuery();
while (rs.next())
{
   String date = rs.getString(1);
   String value = rs.getString(2);
   System.out.println("Generated Date: " + date);
   System.out.println("Generated Value: " + value);
}
rs.close();
call_stmt.close();
conespacxo.close();
}
catch(Exception e)
{
   e.printStackTrace();
}