Saturday 7 April 2012

Thread Deadlock in Java

Thread Deadlock is a special type of error that every Java programmer should try to avoid . Thread deadlock is specially related to multitasking ( i.e. Multithreaded programming ) in java . For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will be blocked . However, if the thread in Y at the same time tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is a difficult error to debug.


Though in general, deadlock occurs rarely, when the two threads try to access synchronized methods defined by each other. It may involve more than two threads and two synchronized objects.


The below java code creates two classes, A and B, with methods dl1( ) and dl2( ), respectively, which pause briefly before trying to call a method in the other class. The main class, named Deadlock, creates instances of A and a B and then starts threads to set up the deadlock condition. The dl1( ) and dl2( ) methods use Thread.sleep()  as a way to force the deadlock condition to occur.



//Program to demonstrate Thread Deadlock

class A{
     synchronized void dl1(B b){
            String name=Thread.currentThread().getName();
            System.out.println(name +" entered A.");
            try{
                 Thread.sleep(1000);  // Stops the executing thread for 1000 ms
                }catch(InterruptedException e){
                        System.out.println(" A Interrupted.");
                    }
                b.last();
                System.out.println(name+"Trying to call last of B.");
       }
        public synchronized void last(){
                System.out.println("Inside A's last.");
            }
        }
class B{
        synchronized void dl2(A a){
             String name=Thread.currentThread().getName();
             System.out.println(name+" entered B");
             try{
                    Thread.sleep(1000);
             }catch(InterruptedException e){
                  System.out.println("B Interrupted.");
              }
              a.last();
              System.out.println(name+" trying to call last of A.");
            }
          public synchronized void last(){
                System.out.println("Inside B's last.");
            }
        }
public class deadlock implements Runnable{
        A a=new A();
        B b=new B();
        deadlock() {
                Thread.currentThread().setName("Main Thread.");
                Thread t=new Thread(this,"Racing Thread.");
                t.start();
                a.dl1(b);
                System.out.println("Back in Main Thread.");
            }
            public void run(){
                    b.dl2(a);
                    System.out.println("Back in other thread.");
                }
            public static void main(String args[]){
                    new deadlock();
                }
            }


P.S. : When running this code in Blu-J ( Win 7 x86 ) your system may be in the 'Stopped Responding' state. :P  Then you'll have to manually kill the process......... :)              


Hope this helps ....... :)


Tuesday 3 April 2012

Java program to handle mouse events


To handle mouse events in Java Applets , you must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window.

The MouseListener interface defines mouseClicked() , mousePressed() , mouseReleased , mouseExited() and mouseEntered() methods while MouseMotionListener interface defines mouseDragged() and mouseMoved() methods. Here's the java code :
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;
public class MouseDemo extends Applet implements MouseListener , MouseMotionListener {
    String msg="";
    int mouseX=0,mouseY=0;
    public void init() {
        addMouseListener(this);
        addMouseMotionListener(this);
    }
     public void mouseClicked(MouseEvent me){
        mouseX=me.getX();
        mouseY=me.getY();
        msg="Mouse Clicked.";
        repaint();
      }
     public void mouseEntered(MouseEvent me){
        mouseX=0;
      mouseX=10;
        msg="Entered.";
        repaint();
     }
     public void mouseExited(MouseEvent me){
      mouseX=0;
      mouseX=10;
      msg="Exited";
        repaint();
     }
     public void mousePressed(MouseEvent me){
      mouseX=0;
        mouseY=10;
        msg="Down.";
        repaint();
     }
     public void mouseReleased(MouseEvent me){
      mouseX=me.getX();
        mouseY=me.getY();
        msg="up.";
      repaint();
     }
     public void mouseDragged(MouseEvent me){
      mouseX=me.getX();
      mouseY=me.getY();
      msg="*";
      showStatus("Dragging mouse at "+mouseX+","+mouseY);
      repaint();
      }
      public void mouseMoved(MouseEvent me){
      mouseX=me.getX();
      mouseY=me.getY();
      showStatus("Mouse is at "+mouseX+","+mouseY);
      }
    public void paint(Graphics g) {
        g.drawString(msg,mouseX,mouseY);
    }
}

After building the .class file you can embed this code in an HTML file using the below tag to run the applet in a Web Browser.

<applet source="MouseDemo" width=300 height=100>
</applet>

You can also use an in-built applet viewer ( like the one present in Blue-J ) to demonstrate the created applet .

Hope this helps :)

Sunday 1 April 2012

Java program to connect to a database Contd.

In my last post related with JDBC I mentioned only about creating tables and inserting new values to a database file using SQL statements. According to comments left by visitors today I am going to post on updating and deleting a particular record. For update or deletion of a record you will have tobe sure that the particular record actually exists in database. If this condition is not checked and you try to modify a non-existing record then you will get a run-time exception. So to avoid this first search for this record using an id(which must be unique) as below written code :
Statement stmt=con.createStatement(); //con is Connection object
ResultSet rs=stmt.executeQuery("SELECT Roll FROM Records");
//Roll is the unique id
         int an=0; 
         boolean found=false;        
         while(rs.next() && found==false){
            an=rs.getInt(0); 
//0 as Roll. is the first column
            if(an==Integer.parseInt(enter_id))  //enter_id is input id
                    found=true; 
//if id is found in database
            }

 Now you can modify or delete using id if found is true like below shown code :
if(found)  //then do anyone of below

  stmt.execute("UPDATE Records SET Sname="+n+" WHERE Roll="+enter_id); //for changing a value

  stmt.execute("DELETE Records WHERE Roll="+enter_id); //for deleting a record

Read this first -->Java program to connect to a database