Sunday, April 26, 2015

Serialization

package com.sync;

import java.io.Serializable;

public class Student implements Serializable {
    int id;
    String name;

    public Student(int idVal, String nameVal) {
        this.id = idVal;
        this.name = nameVal;
    }
}


package com.sync;

import java.io.*;

class Persist {
    public static void main(String args[]) throws Exception {
        Student s1 = new Student(211, "renu");

        FileOutputStream fout = new FileOutputStream("f.txt");
        ObjectOutputStream out = new ObjectOutputStream(fout);

        out.writeObject(s1);
        out.flush();
        System.out.println("success");
    }
}

Synchronization

package com.sync;

class Table {

    synchronized void printTable(int n) {// method not synchronized
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(400);
            } catch (Exception e) {
                System.out.println(e);
            }
        }

    }
}

class MyThread1 extends Thread {
    Table t;

    MyThread1(Table t) {
        this.t = t;
    }

    public void run() {
        t.printTable(5);
    }

}

class MyThread2 extends Thread {
    Table t;

    MyThread2(Table t) {
        this.t = t;
    }

    public void run() {
        t.printTable(100);
    }
}




Creating test class

package com.sync;

class TestSynchronization1 {
    public static void main(String args[]) {
        Table obj = new Table();// only one object
        MyThread1 t1 = new MyThread1(obj);
        MyThread2 t2 = new MyThread2(obj);
        t1.start();
        t2.start();
    }
}

Tuesday, April 21, 2015

Threads Sample Code

class RunnableDemo implements Runnable {
    //class RunnableDemo extends Thread
   private Thread t;
   private String threadName;
  
   RunnableDemo(String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
  
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread(this, threadName);
         t.start();
      }
   }

   public void run() {
          System.out.println("Running " +  threadName );
          try {
             for(int i = 4; i > 0; i--) {
                System.out.println("Thread: " + threadName + ", " + i);
                // Let the thread sleep for a while.
                Thread.sleep(60*1000);
             }
         } catch (InterruptedException e) {
             System.out.println("Thread " +  threadName + " interrupted.");
         }
         System.out.println("Thread " +  threadName + " exiting.");
       }
      
}



public class TestDemo {
   
    public static void main(String args[])
    {
        RunnableDemo demo = new RunnableDemo("Thread1");
       
        demo.start();
    }

}

Sunday, April 19, 2015

Threads



There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

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. 

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(). 

1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks: 
· A new thread starts(with new callstack).
· The thread moves from New state to the Runnable state.
· When the thread gets a chance to execute, its target run() method will run.

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

· 
New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
· 
· 
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
· 
· 
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
· 
· 
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
· 
· 
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
· 

Monday, April 13, 2015

JDBC Example

package com.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



public class JDBCExample {

public static void main(String arg[]) {

 Connection connection = null;
 //Register the driver class
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Registered!");
         //Creating connection
            //            driver     //service url   / DBName , username, pwd
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            System.out.println("SQL Connection to database established!");

            Statement stmt = connection.createStatement();
            ResultSet rows = stmt.executeQuery("select * from users");
           
            while (rows.next())
            {
             System.out.println(rows.getInt(1));
             System.out.println(rows.getString("username"));
             System.out.println(rows.getString("password"));
           
            }
           
            //Creating thePrepare Statement
           
            PreparedStatement pstmt = connection.prepareStatement("insert into users values (?,?,?)");
            pstmt.setInt(1, 3);
            pstmt.setString(2, "Murali");
            pstmt.setString(3, "pswd1");
           
            //Executing the Query
           
            int norows = pstmt.executeUpdate();
            System.out.println("No. of rows inserted; " +norows);
           
        }
       
        catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found !!");
            return;
        }
        catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            return;
        } finally {
            try
            {
                if(connection != null)
                    connection.close();
                System.out.println("Connection closed !!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

}

Monday, April 6, 2015

JDBC Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {

public static void main(String arg[]) {

Connection connection = null;
//Register the driver class
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Registered!");
        //Creating connection
            //  driver     //service url   / DBName , username, pwd
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "test");
            System.out.println("SQL Connection to database established!");

       
        }
        catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found !!");
            return;
        }
        catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            return;
        } finally {
            try
            {
                if(connection != null)
                    connection.close();
                System.out.println("Connection closed !!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

}

Wednesday, April 1, 2015

ArrayList with Beans

Employee.java (Bean class)

public class Employee {

private int empId;
private String empName;
private int salary;
private String email;

public int getEmpId() {
return empId;
}
public void setEmpId(int employeeId) {
this.empId = employeeId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
String employeedetails = this.empId+","+this.empName+","+this.email+","+this.salary;
return employeedetails;
}
}



ArrayList Implementation
import java.util.ArrayList;
import java.util.Iterator;


public class ListExample {
public static void main(String args[])
{
Employee emp = new Employee();
emp.setEmpId(1);
emp.setEmpName("Murali");
emp.setEmail("murali@gmail.com");
emp.setSalary(60000);
Employee emp1 = new Employee();
emp1.setEmpId(2);
emp1.setEmpName("Renu");
emp1.setEmail("renu@gmail.com");
emp1.setSalary(45000);
ArrayList<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(emp);
employeeList.add(emp1);
Iterator<Employee> itr = employeeList.iterator();
while(itr.hasNext())
{
Employee employee = itr.next();
System.out.println(employee.toString());
System.out.println("Employee id is "+employee.getEmpId());
System.out.println("Employee name is "+employee.getEmpName());
System.out.println("Employee email is "+employee.getEmail());
System.out.println("Employee salary is "+employee.getSalary());
}
}

}