Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, February 8, 2014

"Islands of Isolation" in garbage collection?

you may already know that when an object is not referenced by other objects, it's eligiable for garbage collection. But do you know the following two statemenats are also true?

  • "If an object obj1 is garbage collected, but another object obj2 contains a reference to it, then obj2 is also eligible for garbage collection"
  • "If object obj2 can access object obj1 that is eligible for garbage collection, then obj2 is also eligible for garbage collection"
This is called "Island of Isolation". An "island of isolation" describes one or more objects have NO references to them from active parts of an application.
In When is an object eligible for garbage collection?, we talked about: any object, that are not accessible from root set of references, is eligible for garbage collection. If object obj1 is eligible for garbage collection meaning it is not reachable by any objects from root set of references. Then the garbage collection algorithm tries to find any objects that have ONLY refernce to object obj1 (in this case object obj2) which also become eligible for garbage collection.
If obj2 was accessible from root then the object obj1 would never be eligible for garbage collection in the first place. Therefore, it must be that the object obj2 cannot be referenced from the active part of the program, and so object obj2 is eligible for garbage collection.
Here is an example,

class Person {
   public Person firend;
   public static void main(String[] args) {
     Person obj1 = new Person();
     Person obj2 = new Person();
     obj2.firend = obj1;

     obj1 = null;  //Line A
     obj2 = null;  //Line B

     .....
   }
}

After Line A executes, The object obj2 still has a reference to the object obj1 and the objectobj2 is still referenced by the variable obj2. Therefore, the object obj1 can not be eligable for garbage collection. After Line B exectues, there are no more references to the object obj2. There still is a reference to object obj1 inside the object obj2. Now, the object obj1 and obj2has no reference from root set of references. Therefore, both of objects are eligible for garbage collection.

Thursday, June 10, 2010

How to convert an Object into Byte Array


This is a simple program to convert a java object into byte array, This program comes handy when we try to deep clone an object which is my next blog.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;


/**
 * 
 * @author shailesh.chandra
 *
 */
public class ObjectUtil {

 public static void main(String[] args) throws Exception {

  Object object = new Date();

  byte[] byteArray = convertByteArray(object);

  Object readObject = readByteArray(byteArray);

  System.out.println(readObject);

 }

 /**
  * 
  * @param object
  * @return
  * @throws Exception
  */
 private static byte[] convertByteArray(Object object) throws Exception {
  byte[] byteArray;

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
  objectOutputStream.writeObject(object);

  byteArray = byteArrayOutputStream.toByteArray();
  return byteArray;
 }

 /**
  * 
  * @param byteArray
  * @throws IOException
  * @throws Exception
  */
 private static Object readByteArray(byte[] byteArray) throws Exception {
  ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
  ObjectInputStream objectOutputStream = new ObjectInputStream(byteArrayInputStream);
  Object readObject = objectOutputStream.readObject();

  objectOutputStream.close();
  byteArrayInputStream.close();

  return readObject;
 }

}

Deep Clone a object in Java

Below is the simple program to deep clone a object in java


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 *
 * @author shailesh.chandra
 *
 */
public class DeepCloneExample implements Cloneable, Serializable {

/**
*
*/
private static final long serialVersionUID = 6514927441919765349L;

public static void main(String[] args) throws CloneNotSupportedException {
DeepCloneExample deepCloneExample = new DeepCloneExample();
System.out.println(deepCloneExample);
DeepCloneExample cloneObject = (DeepCloneExample) deepCloneExample.clone();
System.out.println(cloneObject);
}

@Override
protected Object clone() throws CloneNotSupportedException {

Object object = deepClone();
return object;

}

/**
*
* @return
* @throws CloneNotSupportedException
*/
protected Object deepClone() throws CloneNotSupportedException {
DeepCloneExample clone;
try {
clone = null;
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(100);
ObjectOutputStream objectoutputstream = new ObjectOutputStream(bytearrayoutputstream);
objectoutputstream.writeObject(this);
byte abyte0[] = bytearrayoutputstream.toByteArray();
objectoutputstream.close();
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0);
ObjectInputStream objectinputstream = new ObjectInputStream(bytearrayinputstream);
clone = (DeepCloneExample) objectinputstream.readObject();
objectinputstream.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new CloneNotSupportedException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new CloneNotSupportedException(e.getMessage());
}
return clone;

}
}

Wednesday, January 9, 2008

Using CachedRowSet in Java

Number of times we do not want to maintain a persistent connection while extracting query data from a ResultSet object. The production environment where we want to quickly connect to database extract the result and release the connection. As a developer I always desired if it could be possible to return the ResultSet back to user after closing the connection, but resultset requires a db connection to remain open until processing completes. Wouldn't it be cool to have ability to return a ResultSet object to a different class or thin client without losing the results of a query. Using CachedRowSet we have the one to accomplish same task without complex coding involved.


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

import javax.sql.rowset.CachedRowSet;

import com.sun.rowset.CachedRowSetImpl;

/**
 * @author Shailesh Chandra
 *  
 */
public class CachedRowSetExample {

    public static void main(String[] args) throws Exception {
        CachedRowSetExample example = new CachedRowSetExample();
        CachedRowSet cachedRowSet = example.executeQuery();
        while (cachedRowSet.next()) {
            System.out.println(cachedRowSet.getString(1) + "\t" + cachedRowSet.getString(2) + "\t" + cachedRowSet.getString(3));
        }
        cachedRowSet.release();

    }

    public CachedRowSet executeQuery() throws Exception {
        CachedRowSet cachedRowSet = null;
        String query = "select * from TEST1";

        Connection connection = null;
        ResultSet resultSet = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@server:1521:service_name";
            connection = DriverManager.getConnection(url, "shailesh", "shailesh");
            System.out.println("Connection is " + connection);

            PreparedStatement preparedStatement = connection.prepareStatement(query);
            resultSet = preparedStatement.executeQuery();
            cachedRowSet = new CachedRowSetImpl();
            cachedRowSet.populate(resultSet);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {

            if (resultSet != null) {
                System.out.println("Closing resultSet");
                resultSet.close();
            }
            if (connection != null) {
                System.out.println("Closing connection");
                connection.close();
            }

        }
        return cachedRowSet;

    }

}

Displaying an Image from Servlet

package com.shailesh;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet implements Servlet {
    /**
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
    }

    /**
     * 
     * 
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest arg0,
     *      HttpServletResponse arg1)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 
     * 
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest arg0,
     *      HttpServletResponse arg1)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        File file = new File("c:\\myImage.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        int i = 0;
        byte[] buffer = new byte[1024];
        while ((i = fileInputStream.read(buffer)) >= 0) {
            response.getOutputStream().write(buffer, 0, i);
        }
    }

}

Thursday, September 20, 2007

Sending mail from Java

import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {
    private static final java.lang.String MAIL_HOST = "mail.smtp.host";
    private Message message = null;
    private Properties props = null;
    private Multipart multipart = null;
    private String host = "";

    public MailSender() {
        String mailHost = ""; //can be read from property file 
        setHost(mailHost);
        initialize();

    }
    /**
     *param string 
     */
    public MailSender(String mailHost) {
        setHost(mailHost);
        initialize();
    }

    /**
     * intializing code 
     *
     */
    private void initialize() {
        props = System.getProperties();
        props.put(MAIL_HOST, getHost());
        Session session123 = Session.getInstance(props, null);
        message = new MimeMessage(session123);
        multipart = new MimeMultipart();
    }

    /**
     * @param string address of SMTP server 
     */
    protected void setHost(String string) {
        host = string;
    }

    /**
     * 
     * @return address of SMTP server being used
     */
    protected String getHost() {
        return host;
    }

    /**
     * 
     * @param address email address of sender 
     * @throws Exception
     */
    public void setFromRecipient(String address) throws Exception {
        message.setFrom(new InternetAddress(address));
    }

    /**
     * 
     * @param address email address of reciever for TO field,
     * if there are more than one reciever this method can be 
     *  used multiple times    
     * @throws Exception
     */
    public void addToRecipient(String address) throws Exception {
        message.addRecipient(
            Message.RecipientType.TO,
            new InternetAddress(address));
    }

    /**
     * 
     * @param address email address of reciever for CC field,
     * if there are more than one reciever this method can be 
     *  used multiple times
     * @throws Exception
     */
    public void addCCRecipient(String address) throws Exception {
        message.addRecipient(
            Message.RecipientType.CC,
            new InternetAddress(address));
    }

    /**
     * 
     * @param address email address of reciever for BCC field,
     * if there are more than one reciever this method can be 
     *  used multiple times
     * @throws Exception
     */
    public void addBCCRecipient(String address) throws Exception {
        message.addRecipient(
            Message.RecipientType.BCC,
            new InternetAddress(address));
    }

    /**
     * 
     * @param subject - subject for the mail
     * @throws Exception
     */
    public void setSubject(String subject) throws Exception {
        message.setSubject(subject);
    }

    /**
     * 
     * @param filename - the name of file to be attached
     * @param filePath - the path of file to be attached
     * @throws Exception
     */
    public void attachFile(String filename, String filePath) throws Exception {

        DataSource source = new FileDataSource(filePath);
        // Set the data handler to the attachment
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        // Set the filename
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
    }

    /**
     * 
     * @param messageText - message content
     * @throws Exception
     */
    public void setMessage(String messageText) throws Exception {
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(messageText);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
    }

    /**
     * 
     * @return
     */
    public void sendmail() {
        try {
            Transport.send(message);
            System.out.println("Mail sent successfully");

        } catch (Exception e) {

            e.printStackTrace();
            System.out.println("There was some problem, mail not sent. " + e.getMessage());

        }
    }

    /**
     * 
     * @param argv
     * @throws Exception
     */
    public static void main(String argv[]) throws Exception {

        MailSender mailSender = new MailSender("PUT_SERVER_IP_HERE");
        mailSender.setFromRecipient("I_AM_SENDER@domain.com");

        mailSender.setSubject("How are You?");

        mailSender.addToRecipient("receiver1@domain.com");
        mailSender.addToRecipient("receiver2@domain.co");

        mailSender.addCCRecipient("CCreceiver1@domain.com");
        mailSender.addCCRecipient("CCreceiver2@domain.com");

        mailSender.addBCCRecipient("BCCreceiver1@domain.com");
        mailSender.addBCCRecipient("BCCreceiver2@domain.com");

        mailSender.attachFile("File Name", "FILE PATH");
        mailSender.attachFile("Another File Name", "ANOTHER FILE PATH");

        mailSender.setMessage("Hello, \n\n How are.\n\nThanks.\n");

        mailSender.sendmail();

    }

}