Pages Navigation Menu

Coding is much easier than you think

What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

Posted by in Java

 
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally block is NOT called in following conditions

  • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.
  • if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
  • If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.


Read More

What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?

Posted by in Java, JVM

 

What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?


This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. 

Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered

1. java.lang.OutOfMemoryError: Java heap space

The quick solution is to add these flags to JVM command line when Java runtime is started:
-Xms1024m -Xmx1024m
 

2. java.lang.OutOfMemoryError: PermGen space

The solution is to add these flags to JVM command line when Java runtime is started:
-XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled

Long Term Solution :


Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.

Read More

Performance comparison of different for loops in java

Posted by in Core Java, Java

 
In this post, we will compare the performance of different for loops in java
 

Different ways to use for loop

 
1) For each statement
 
In this technique, advanced for each statement introduced in java 5 is used.
 

 
private static List<Integer> list = new ArrayList<>();
for(Integer i : list)
{
    // code stuff
}

 

2) Using list.size() in condition
 

 
private static List<Integer> list = new ArrayList<>();
for(int j = 0; j < list.size() ; j++)
{
    // code stuff
}

 
3) Initialize another local variable with size
 

private static List<Integer> list = new ArrayList<>();
int size = list.size();
for(int j = 0; j < size ; j++)
{
    // code stuff
}

 
4) Initialize the initial value of counter to size of list
 

private static List<Integer> list = new ArrayList<>();
for(int j = list.size(); j > size ; j--)
{
    // code stuff
}

 

Comparing the performance of all types

 

import java.util.List;
import java.util.Calendar;
import java.util.ArrayList;
 
public class ForLoopPerformance
{

    private static long startTime;
    private static long endTime;

    private static List<Integer> list = new ArrayList<>();

    static
    {
        for(int i=0; i < 10000000; i++)
        {
            list.add(i);
        }
    }

    public static void main(String[] args)
    {
        //Type 1
        startTime = Calendar.getInstance().getTimeInMillis();
        for(Integer i : list)
        {
            //
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("For each loop :: " + (endTime - startTime) + " ms");
 
        //Type 2
        startTime = Calendar.getInstance().getTimeInMillis();
        for(int j = 0; j < list.size() ; j++)
        {
            //
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
 
        //Type 3
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();
        for(int j = 0; j < size ; j++)
        {
            //
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int size = list.size(); int j = 0; j < size ; j++] :: "
        + (endTime - startTime) + " ms");
 
        //Type 4
        startTime = Calendar.getInstance().getTimeInMillis();
        for(int j = list.size(); j > size ; j--)
        {
            //
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int j = list.size(); j > size ; j--] :: "
        + (endTime - startTime) + " ms");
    }
}

 

Run it :

 

For each loop :: 116 ms
Using collection.size() :: 36 ms
Using [int size = list.size(); int j = 0; j < size ; j++] :: 4 ms
Using [int j = list.size(); j > size ; j--] :: 1 ms

 

Reason for difference in performance

 
Type 1 is costliest one and simple reasoning is the use of iterator internally created in for each loop. Creating an iterator and calling iterator.get() adds up to most of cost which is not involved in direct access in other three types.

Type 2 uses size() method call every time and thus on runtime it brings a little overhead. Though JVM optimizes this code as inline call and other optimizations also and size method is simply a getter for size attribute of instance of list. Even though it brings a few more statements to execute at machine level code and which makes the difference.

Type 3 and 4 have a very little difference and should be considered as same, they both fetch the size of collection initially. And then uses this size value in loop for checking the condition.

Read More

Does garbage collection guarantee that a program will not run out of memory?

Posted by in Core Java

 
Garbage collection does not guarantee that a program will not run out of memory. It is perfectly possible for a programmer to mistakenly create objects which never go out of scope, thus consuming more and more memory until all heap is exhausted.

It is the programmer’s responsibility to ensure that objects no longer in use are no longer referenced by the application. That way the garbage collector can do its job and reclaim memory used by these objects.

Automatic garbage collection only means that garbage (i.e., unreferenced memory) is automatically collected (i.e., reclaimed for further use). If you keep references to it, it’s not garbage, and not collected.

Read More

Sending email with attachment using JavaMail API

Posted by in Java

 

For sending email with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc.
 

For sending email using JavaMail Api you need to import 2 jar files:

1.mail.jar
2.activation.jar

 

There are total 7 steps for sending attachment with email. They are:

1. Get the session object 2. Compose message 3. Create MimeBodyPart object and set your message text 4. Create new MimeBodyPart object and set DataHandler object to this object 5. Create Multipart object and add MimeBodyPart objects to this object 6. Set the multiplart object to the message object 7. Send message


package com.simplecode.email;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import javax.mail.Session;
import javax.mail.Message;
import javax.mail.BodyPart;
import javax.mail.Transport;
import javax.mail.Multipart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;

public class JavaEmailAttachment {

	Properties emailProperties;
	Session mailSession;
	MimeMessage message;
	// Create the message part
	BodyPart messageBodyPart;
	// Create message part for attaching file
	BodyPart messageFilePart;

	// Create a multipart message
	Multipart multipart;

	public static void main(String arg[]) throws AddressException,
			MessagingException {

		JavaEmailAttachment javaEmail = new JavaEmailAttachment();

		javaEmail.setMailServerProperties();
		javaEmail.createEmailMessage();
		javaEmail.sendEmail();
	}

	public void setMailServerProperties() {

		// gmail's smtp port
		String emailPort = "587";
		emailProperties = System.getProperties();
		emailProperties.put("mail.smtp.port", emailPort);
		emailProperties.put("mail.smtp.auth", "true");
		emailProperties.put("mail.smtp.starttls.enable", "true");
	}

	public void createEmailMessage() throws AddressException,
			MessagingException {
		String[] toEmails = { "[email protected]" };
		String emailSubject = "Java Email";
		String emailBody = "This is an email sent by JavaMail api";

		// 1. Get the session object
		mailSession = Session.getDefaultInstance(emailProperties, null);
		// 2. Compose message
		message = new MimeMessage(mailSession);

for (int i = 0; i < toEmails.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}

		message.setSubject(emailSubject);

		// 3. Create MimeBodyPart object and set your message text
		messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText(emailBody);

		// 4. Create new MimeBodyPart object and set DataHandler object to this
		// object - for attachment

		messageFilePart = new MimeBodyPart();

		String filename = "JavaEmail.java";
		String fileloc = "C:/Users/Nisha/Desktop/JavaEmail.java";
		DataSource source = new FileDataSource(fileloc);
		messageFilePart.setDataHandler(new DataHandler(source));
		messageFilePart.setFileName(filename);

		// 5. Create Multipart object and add MimeBodyPart objects to this
		// object

		multipart = new MimeMultipart();

		// Set the body and file
		multipart.addBodyPart(messageBodyPart);
		multipart.addBodyPart(messageFilePart);

		// 6. set the multiplart object to the message object

		message.setContent(multipart);

	}

	public void sendEmail() throws AddressException, MessagingException {
		String emailHost = "smtp.gmail.com";

		// just the id alone without @ gmail.com
		String senderUsername = "your emailid here";
		String senderEmailPassword = "your email password here";

		// 7. send message

		Transport transport = mailSession.getTransport("smtp");

		transport.connect(emailHost, senderUsername, senderEmailPassword);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		System.out.println("Email sent successfully.");
	}

}

 

dwd2
Download It – JavaEmail
Read More
Page 1 of 1512345...10...Last»