Follow @abushalihu Abu The Geek

Thursday, December 15, 2011

Threads in Java (level: Beginner with good knowledge in Java program)

      I did not think that there is no most interesting and/or difficult features available in Java other than Thread like C had pointers. Any Java developer who is really unaware of threads also had written thread programs!. Trust me, I am not lying. It is true!.

Normally, every Java program starts its execution by a thread called the Main thread. So what does a thread mean?

Thread
-------------
A Thread is a separate path of execution in a process or program. More specifically a threads job is to get the CPU cycles (probably when the CPU is idle) to execute some set of codes of a program for a while or long.

Main Uses of Threads (These three bullets must be in your mind when thinking about threads)
---------------------------
1.    To utilize the CPU cycles as much as possible
2.    To introduce the Asynchronous behaviour
3.    To have Parallellism or treat a single processor as Multiprocessor

Multithreading
--------------------
In a single threaded program when you run any of your program many time the CPU could be in idle state. For example your program might be blocked for any input from the User, File, Socket or even some other program. In such a time the CPU is idle. So it is better to have any other threads to fully utilize the CPU's idle time. By doing so, we can reduce the CPU's idle time.

Multithreading is a specialized form of multitasking. In multitasking more than one procesess could run concurrenty. Multithreading on the other hand that more than one threads could run on a single process. Some differences are there between them. In multithreading two threads shares the same process meaning that threads are running on the same address space.

How to create a Thread
------------------------------
There are two categories to create threads.

1.    By Implementing Runnable Interface
2.    By Extending Thread Class

Runnable having only one method called run method. This is the method from which a thread starts its execution.
Thread class having some usefull methods such as getName(), currentThread(), start(), stop(), sleep() and etc.

Sample program (Implementing Runnable Interface)
-----------------------------------------------------------------
class ConzolePrinter implements Runnable {
private String printMessage;

ConzolePrinter(String text) {
    printMessage = text;
}

//Threads entry point.
public void run() {
    print(printMessage);
}

public void print(String text) {
    for(int i=0; i < 5; i++) {
        System.out.println("Text = " + text + " Printed by " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch(InterruptedException e) {
            System.err.println("Thread Interrupted " + e +" on thread "+ Thread.currentThread().getName());
        }
    }
    System.out.println(Thread.currentThread().getName() +" Exiting...");
}

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

Runnable printerA = new ConzolePrinter("Hello");
Runnable printerB = new ConzolePrinter("World!");

Thread childThreadA = new Thread(printerA, "Thread-A");        // creating a child thread.
childThreadA.start();                        // starting a thread

Thread childThreadB = new Thread(printerB, "Thread-B");
childThreadB.start();

Thread mainThread = Thread.currentThread();        // returns currently executing thread. in this case it is main thread since it is main method.
mainThread.sleep(10000);                    // Sleeping main thread for 10 seconds to wait for the child threads to complete.
System.out.println(mainThread.getName() +" Exiting...");
}
}


Program Explanation
--------------------------
The ConzolePrinter class implements Runnable and overrides its run method and ConzolePrinter have its own method print to print a message into the console.

The main method creates two ConzolePrinter objects with the printMessage as argument. Two child threads are created namely childThreadA and childThreadB with the Runnable object as argument.

The two child threads get started by calling its start method. When calling start method of a thread the JVM will invoke the run method of the threads Runnable object.

The print method print a message for 5 times. For every print it sleeps the current thread for 1 second to enforce asynchronous execution behaviour. The main thread sleeps for 10 seconds for the two child threads to finish its task.

Exercise:
-------------
You try the same above program by extending a Thread class.

Note: I will be updating more on Threads as much as I learn from today onwards .

Saturday, November 12, 2011

Google Open Source Blog: Introducing Closure Stylesheets

Google Open Source Blog: Introducing Closure Stylesheets: (CSS is for programming, not for pasting) When the Closure Tools were first released a little over two years ago, they gave web developers...

Thursday, October 13, 2011

Microsoft Exchange Connector - Exchange Web Services (EWS) API in Java

     Hi! Friends... After a long gap I would like to share an useful Java API called EWS.
Exchange Web Services (EWS) is an open source Java API written by Microsoft. This API provides developers programmatic access to Microsoft Exchange Servers (Versions 2007 and above) through Java. The latest version is 1.1.5. By using the API you can send, receive emails. To use this API in your Java program you have to download and install the below third party libraries. In the given version 1.1.5 there was an issue with handling of Control Characters. That API failed to handle the Control Character's. I found that issue when i receive an email which contains Control Characters from MS Exchange Server 2010. I have upgraded this API to 1.1.5.1 in which i have removed all the Control Characters.

Pre-requisites

Download and install the Java SDK

The below required libraries included in the lib directory.

Apache Commons HttpClient 3.1
Apache Commons Codec 1.4
Apache Commons Logging 1.1.1
JCIFS 1.3.15

Accessing EWS by using the EWS Java API
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("emailId@domain.com", "password");
service.setCredentials(credentials);
To set the Exchange webservice URL
String uri = https://hostName/ews/Exchange.asmx;
URI uriObj = new URI(uri);
service.setUrl(uriObj);

Here hostName is your exchange server's domain name. (eg. mail.microsoft.com)

To set the Exchange webservice URL by Autodiscover
service.autodiscoverUrl("<your e-mail address>");
The autodiscoverurl method takes your emailId as argument and it automatically fetches the exchange webservice's nearest endpoint.
You have to set your endpoint URL by manually or using autodiscovery but not both!.

Sample Program to receive unread emails in inbox from MS Exchange Server:

import java.net.URI;
import java.util.Iterator;
import microsoft.exchange.webservices.data.ConflictResolutionMode;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.EmailMessageSchema;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.SortDirection;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;

class EWSReadEmail {
public static void main(String args[]) throws Exception {
    ExchangeService service = new ExchangeService();
    ExchangeCredentials credentials = new WebCredentials("emailId@domain.com", "password");
    service.setCredentials(credentials);
    URI uri = new URI("https://yourhostname/ews/Exchange.asmx");
    service.setUrl(uri);
    ItemView view = new ItemView(100);    //Read maximum of 100 emails
    view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Ascending);    // Read emails by received date order by Ascending
    FindItemsResults < Item > results = service.findItems(WellKnownFolderName.Inbox, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), view);    //Read only unread emails in inbox
    Iterator<Item> itr = results.iterator();
    System.out.println("Total Unread Emails="+ results.getTotalCount());
    while(itr.hasNext()) {
        Item item = itr.next();
        ItemId itemId = item.getId();
        EmailMessage email = EmailMessage.bind(service, itemId);
        System.out.println("Sender= " + email.getSender());
        System.out.println("Subject= " + email.getSubject());
        System.out.println("Body= " + email.getBody());
        email.setIsRead(true);        //Set the email to read.
        email.update(ConflictResolutionMode.AlwaysOverwrite);
    }
    }
}
You can download the source and binaries here

Thursday, September 8, 2011

SpringSocial!

     Hi Friends.... I just begin my debate article with the most widely used opensource framework Spring!. Spring Social is an extension of the Spring Framework that allows you to connect your applications with social websites such as Facebook, Twitter, LinkedIn and GitHub. Using SpringSocial you can access your commercial websites accounts. For more information i have given few urls which can be used to dig into SpringSource.


Home page:
===========
http://www.springsource.org/spring-social

Quick Start Guide
===============
https://github.com/SpringSource/spring-social/wiki/Quick-Start

Samples
==========
https://github.com/SpringSource/spring-social-samples

Forums
==========
http://forum.springsource.org/forumdisplay.php?82-Social

OAuth Tutorials
==========
http://hueniverse.com/2007/10/beginners-guide-to-oauth-part-ii-protocol-workflow/

If i did any mistake please forgive me and help me to correct it. Comments from friends and visitors are welcome.