Advertisements

Multithreading in Java

Multithreading

Usually a program has logic to execute and some objects or data to modify. In a single threaded system program executes in a sequence line by line. Multithreaded system can allow multiple threads to execute a program parallel in multiple instances. If there is any part of code dealing with the object data modification, there is no guarantee that it will not be attempted any more than one thread at a time.

Now there a need to make sure that such kind of code should be executed exclusively. To achieve this in Java we a concept of LOCK. Using Lock mechanism thread holds complete hold on an object and object is also can not be access any other thread except the thread holding that lock. Lock is an object level control and one thread only can hold it at a time.

Synchronized: We have to specify about the piece of code in a program which should be run exclusively. It could be a code segment or a complete function. Synchronised can be used in following ways:

Function level synchronise will fetch a lock on the object, this function is defined in.

1)  synchronised function updateTotal(){
       // some code
    }

2)  a block of code can also be defined as synchronised with an specified object, to capture a lock control on.

function updateTotal(){
     // some code 
     Synchronised(this){
     //some code
     }
}

Thread Sates or Life cycle. Thread follwos a life cycle, which starts from the threation till it is destroyed.

multith

  •  A thread can be in one of the following states:

    • NEW
      A thread that has not yet started is in this state.  This is the first state when thread object is created. Thread will be in this state until the run method is not called of.
    • RUNNABLE
      A thread executing in the Java virtual machine is in this state. Once the run method is called, thread goes in the runnble state.  While it is in a runnable state it is eligible to get process time to execute its part. Process though will keep distributing the time among all the active threads. Thread can also move to waiting state due to two reasons. 1 Timed waiting 2: Object waiting. Threads not in runnable states do not get process time.
    • BLOCKED
      A thread that is blocked waiting for a monitor lock is in this state.
    • WAITING
      A thread that is waiting indefinitely for another thread to perform a particular action is in this state.Some time a thread need a lock on a object and that object is being used bus another prohram or thread, in this case thread will wait for this object untill the object is not free. Some time this can cause a deadlock schenario if there is a possiblility that threads are using same objects in multiple situations and if the program is not designed properly.
    • TIMED_WAITING
      A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. Tread is forced to wait for some period of time may be by using Thread.sleep method. It will automatically come back to runnable state once specifiled time is over.
    • TERMINATED
      A thread that has exited is in this state.

    A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states. Ref :  http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html

 

Inter Thread Communication: When threads are trying to access a common object and that is bieng used by another thread. Theres has to be some way to notify the waiting threads once that object becomes free. This is achieved by wait,notify, notifyAll machanism. Wait and Notify is a machanism by which we can send signals between the thread when some specific condition is met.

Lets understand by the example of >> Producer and Consumer Problem in Java
======================================

import java.util.ArrayList;
import java.util.Random;
//Shared resource
class Pool{
   ArrayList pool = new ArrayList();
   int maxSize=10;
   public synchronized String popItem(){
   if(this.pool.size() = maxSize){
     System.out.println("List Full !" + this.pool.size());
     try {
      wait();
     } catch (InterruptedException e) {
      LOG.error("Interrup has occured");
      e.printStackTrace();
     }
   }
   notify();
   pool.add(item);
 }
}

//Supplier Thread
class Supplier extends Thread{
  Pool poolSet;
  public Supplier(Pool poolSet) {
     this.poolSet = poolSet;
     this.setName("Supplier");
  }

 public void run() {
   while(true){
   String rand = new Random().toString();
   System.out.println(this.getName()+" Adding " + rand);
   poolSet.pushItem(rand);
   try {
     Thread.sleep(1000);
   } catch (InterruptedException e) {
      LOG.error("Interrupt has occurred");
      e.printStackTrace();
   }
 }
}
}

//Consumer Thread
class Consumer extends Thread{
  Pool poolSet;
  public Consumer(Pool poolSet) {
   this.poolSet = poolSet;
   this.setName("Consumer");
  }
 public void run() {
 while(true){
    System.out.println(this.getName()+" Read: " + poolSet.popItem());
    try {
       Thread.sleep(10000);
    } catch (InterruptedException e) {
       e.printStackTrace();
    }
    }
  }
}

//Test case
public class TestThread {
   public static void main(String[] args){
   Pool mypool = new Pool();
   Supplier sup = new Supplier(mypool);
   Consumer con = new Consumer(mypool);
   con.start();
   sup.start();
 }
}

======================================

Above Example demonstrate three classes Pool , Consumer and Supplier as all are part defined under the main program so that class Consumer and Supplier have direct access to the object of Class Pool.

Otherwise if they are we can also pass PoolC class object to Consumer and Supplies class constructor if they are not under a same class.

Notify() and NotifyAll(): It’s a good question to ask that what’s difference between notify() and notifyAll() methos. Notify() method will send a signal to one of the thread waiting for the same object (this may depend on any criteria like thread priprity or it can also be random). Whereas notifyAll() will send signal to all the threads who are waiting for that object and then it is upto the processor which therads it allows to execute.

Sleep() method: Sleep method is a static method and called from the Thread class directly. Thread.sleep(100) and it throws intereuptException, so you have to catch it also.

wait() method: Wait is the method of Object class and should always be called from the synchronised block of code. Advised to use wait(long timeOut)

Thread Interruption: Each thread has a boolean property associated with it which represents its interrupt status. When a thread is interrupted by some other thread by calling its Thread.interrupt() method then one of the two things happen

a) If a thread is executing low level incorruptible method like sleep() wait() pr join() then it unblocks them and throws InterruptedException.

b) Otherwise interrupt() just sets the internal flag value of the interrupted thread to true, that why is is recommended to check its status by calling isInterrupted() in threads normal business. When isInterrupted() returns true that means it is signal to stop the thread execution.

Advertisements

Create Dynamic PDF from Java Appplication

Article is Under Writing.

Generate and Send an Excel file from J2EE WebApplication

Generating Excel file in J2EE Server.

 

This article is written to describe a simple way of generating an Excel file in Java. We will be using an open source Java Excel API  ( jxl http://jexcelapi.sourceforge.net/ ) to dynamically generate an excel file and reading and modifying an existing excel file.

 

Using this technology we can directly generate an Excel file on the fly on a user request.

In a typical web application a user can request for an excel sheet based report from a web based application.

 

With the proper integration of this API and the server side backend data layer, we can transform the fetched data into an excel sheet. Later this excel sheet can be sent to client side using proper http response header information.

 

To begin with the application we need to download the jxl.jar file and put it under the project folder.  To download go to the URL: http://sourceforge.net, and under File section you have a link to download the required jar files.

 

 

Code side view:

We may need following classes depending on our need:

1)

import jxl.Workbook;

import jxl.format.Colour;

import jxl.format.UnderlineStyle;

import jxl.write.Label;

import jxl.write.Number;

import jxl.write.WritableCellFormat;

import jxl.write.WritableFont;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;

 

 

2) Create workflow object:

WritableWorkbook  wrtWorkbook = Workbook.createWorkbook(new

File(“MyExcel.xls”));

WritableSheet sheet1 ;

 

This function will create a writable workBook object. We can specify the location of the Excel file otherwise it will create in the current running folder. Later using defined API’s we can add worksheets on this workbook.

Note in case on reading excel sheet, we need to create WorkBook class

Object not WritableWorkBook.

 

 

3) Create worksheet :

sheet1 = this.wrtWorkbook.createSheet(“Sheet1”,0);

params: sheetname and location.

Here we have created a worksheet for the workbook, minimum one worksheet is required for a workbook to write some data in it. Like an Excel file one workbook can also contain more that one Sheet.

 

4) Adding cells :

sheet1.addCell(number);

Once the sheet object is created, we will use following API to write data in the specified cells. Here we are giving very simple demonstration but if require it also supports various kind of formatting.

To add number

Number number = new Number(colIndex, rowIndex, num);

sheet1.addCell(number);

 

To add string

Label label = new Label(colIndex, rowIndex, str);

sheet1.addCell(label);

 

5) Formatted Data

We can also specify specific format by using defined format classes:

WritableFont times10font = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BROWN);

 

WritableCellFormat times10format = new WritableCellFormat

Label label = new Label(colIndex, rowIndex, str, times10format );

 

 

6) Closing Worksheet

wrtWorkbook.write(); this function will write sheet into workBook

wrtWorkbook.close();

 —————————————————————–

  

Sending an Excel file along with the HTTP Response.

 

In a typical J2EE web application an http Request is processed in doGet\doPost method and a response is generated and send back to the client. We need to set response header to provide specific information about the content it carrying, so that browser can automatically detect the compatible application to open that.

resp.setHeader(“Cache-Control”, “max-age=30”);

resp.setContentType(“application/vnd.ms-excel”);

 

application/vnd.ms-excel defines that it is an excel spreadsheet application.

We can defile to send content in inline format or as an attachment.

resp.setHeader(“Content-disposition”,“inline; filename=MyExcel.xls);

 

here using java.io API’s we will write Excel file content in the response object.

 

ServletOutputStream sos = response.getOutputStream();

FileInputStream fio = new FileInputStream(“./” + “MyExcel.xls”);

 

while((c = fio.read()) != -1) {

          sos.write(c);

}

 

And that’s all. Its all set and Please go and receive the Excel file in the client’s browser.

 

Regards

Manjul  

 

 

WEB 2.0 – AJAX

Introduction to …         WEB 2.0                    Why AJAX         RICH Internet Application         DOJO         JSON          Web 2.0, pronounced “web two point oh” , a phrase coined by O’Reilly Media in 2003         Second generation of web-based communities and hosted service         Internet Usage is drastically changed         Which facilitate collaboration and sharing between users          Such as social-networking sites,wikis and folksonomies         User is part of Application Life Cycle         Web 2.0 is the business revolution in the computer industry caused by the move to the internet as platform §          Characteristics of “Web 2.0” §          “Network as platform”§          Users owning the data on a site and exercising control over that data.§          An architecture of participation that encourages users to add value to the application as they use it.§          A rich, interactive, user-friendly interface based on Ajax or similar frameworks.§          Some social-networking aspects §          Technology Overview  “Web 2.0” §          Rich Internet Application techniques, optionally Ajax based§          CSS§          Semantically valid HTML markup and the use of microformats§          Syndication and aggregation of data in RSS/Atom§          Clean and meaningful URLs§          Use of Open source software either completely or partially§          Weblog publishing §          Mashup §          AJAX – The Detail… §          Allows user to continue interacting with web page while waiting for data to be returned§          Page can be updated without refreshing browser§          Results in a better user experience§          There are AJaX libraries that reduce the amount of JavaScript code that must be written§          Not dependent on any language or data structure§          Works with XHTML and JAVAScript§          Dynamic display an interaction using the Document Object model§          Asynchronous data retrieval using XMLHttpRequest§          Javascript binding Every thing together §          XMLHttpRequest §          JavaScript XMLHttpRequest object§          With this object, your JavaScript can trade data with a web server, without reloading the page§          Allows HTTP Request to be sent from JavaScript code§          HTTPResponse are processed by the handler functions, in the client side§          Browser dependent   §          XMLHttpRequest Object Properties          readyState                        – 0 = UNINITIALIZED; open not yet called                        – 1 = LOADING; send for request not yet called                        – 2 = LOADED; send called, headers and status are available                        – 3 = INTERACTIVE; downloading response,                                    responseText only partially set                        – 4 = COMPLETED; finished downloading response         responseText                        – response as text; null if error occurs or ready state < 3         responseXML                        – response as DOM Document object; null if error occurs or ready state < 3         status                         – integer status code         statusText                         – string status §          XMLHttpRequest Object Methods§          Basic methods§                      – open(method, url[, async]) – initializes a new HTTP request§                                  • method can be “GET”, “POST”, “PUT” or “DELETE”§                                  • url must be an HTTP URL (start with “http://&#8221;)§                                  • async is a boolean indicating whether request should be sent asynchronously§                                  – defaults to true§                      – send(body) – sends HTTP request§                        abort() – called after send() to cancel request §                      §          Header methods§                      – void    setRequestHeader(name, value)§                      – String getResponseHeader(name)§                                  Returns the string value of a single header label §                      – String getAllResponseHeaders()§                                  Returns a string where “header: value” pairs are delimited by carriage returns§            §          Rich Internet Applications (RIA) §          Unlike traditional web applications centered all activity around a client-server architecture with a thin client§          Web applications that have the features and functionality similar to desktop applications§          Run in a Web browser, or do not require software installation§          Intermediate layer of code, often called a client engine, between the user and the server§          Features:§                                  -Richer.§                                  -More responsive§                                  -Client/Server balance§                                  -Asynchronous communication§                                  -Network efficiency and more…§          Tools:§                                  -JavaScript§                                  -Adobe Flash§                                  -Microsoft Silverlight§                                  -Sun Microsystem JavaFX§                                  -Java Applets and more…  §          DOJO§          Dojo is an Open Source DHTML toolkit written in JavaScript§          Designed to ease the rapid development of JavaScript- or Ajax-based applications and web sites§          Dojo provides to make your web sites more usable, responsive, and functional§          Provides API for Event system, I/O APIs, and generic language enhancement§          You can use the Dojo build tools to write command-line unit-tests for your JavaScript code  §          DOJO Features§          Widgets: Dojo widgets are prepackaged components of JavaScript code, HTML markup and CSS style declarations that can be used to enrich websites with various interactive features that work across browsers: ex : Menus, tabs etc§          Asynchronous communication§          Dojo provides an abstracted wrapper “dojo.io.bind”§          JavaScript programming§          Packaging system: Packaging system to facilitate modular development of functionality in individual packages and sub-packages§          Dojo File Upload§          Client-side data storage: In addition  to cookies Dojo also provides a local, client-side storage abstraction named Dojo Storage  §          JSON§          JSON (JavaScript Object Notation) is a lightweight data-interchange format. §          Generic Data Structure for data exchange between client and server.§          Text format that is completely language independent but uses conventions that are familiar to programmers of most of the languages, including C, C++, C#, Java, JavaScript, Perl, Python etc.  §          Client Side JSON   Creating the JSON string.  var myJSONObject = {“bindings”: [        {“ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”},        {“ircEvent”: “PRIVMSG”, “method”: “deleteURI”, “regex”: “^delete.*”},        {“ircEvent”: “PRIVMSG”, “method”: “randomURI”, “regex”: “^random.*”}   ] };                                                                                                                           myJSONObject.bindings[0].method // “newURI” . Fetching the JSON Value retrieved from Server                                                                    var myObject = eval(‘(‘ + myJSONtext + ‘)’);  §          Server Side JSON         JSON is supported by most of the server side language JAVA, ASP, PHP etc.         Creating a JSON Object                        JSONObject  jObj = new JSONObject();                        jObj.put(“key”, value);         Retrieve JSON data from the Client             String jsonStr = request.getParameter(“actionString”);                        JSONObject jobj = (JSONObject)JSONValue.parse(jsonStr);                        String actionName = jobj.get(“key”);   

Last Dipawali ….when we were in school.

Last Dipawali ….when we were in school .

Today is 17th October just three days are left for our grand celebration Diwali.  We are so exited about going home and meet our neighbors and friends .     I can easily differentiate the changes , taking place in our mind with the time and surrounding…

I remember those days when we were in schools….Diwali celebration was like :

We started making plans for diwali from more one month before. After leaving from the schools we used to see the market ..not one but 10 times before the final day. We started making string of light bulbs called “Jhalars” from a month back so that at the end time we can decorate fully and better than our last years competitors. As days were coming close we also have to go to the tailors to get our dress ready and fighting with parents for not taking us for our shopping. We also had to do some home-work, as a team member of our PM …I means our mom , she was keep on asking have you cleaned that corner , have you brought that “saman” goods. We also had to go for bringing diwali sweets and “namkeens”.

Finally its a time of going to market and purchase crackers,…. again we got less money, we need more and mom is saying why are you wasting that much of money in crackers but thanks god dad is with us . So we used to go with him and after bringing them, and did not forget to put them in sun-light so that in the night they will give more sound output. Finally diwali evening has come and parents are calling us from ground floor room to come down and do the pooja , I am calling my brother to come down and he is busy in lightening the crackers with his friends. Ok he came and pooja is started (it took around 1 hour ) after that we lighten the whole home with small light lamps ( I specially like this particular part of diwali very much) . Oh god what happened to this “Jhalar” its not working now we need to check it again…after some trouble finally it was started blinking. Now we are going for crackers my brother has already cracked half of his… and now asking mines…I used to give him bombs and rockets coz I like to see them from distant place but flower pot “anar” and fire wheel charkhee is still my unfavorite one.

We also had to go to our neighbor’s home to wish them happy diwaali and eat sweets and namkeens though most of the things are similar . Now lets take dinner and watch tv till late night ( usually diwali night all the channels showed a block buster movie) and then finally go to sleep.

Sweet Dreams……. becous these are only DREAMS now…..!

RFID Radio Frequency Identification.

What is RFID .

Radio Frequency Identification (RFID) is an radio waves sensor technology, relying on storing and remotely retrieving data using devices called RFID tags readers. An RFID tag is a small chip that can be attached to an object it could be a simple box or an animal, or person for the purpose of identification using radio waves. Chip-based RFID tags contain silicon chip and antenna. Passive tags require no internal power source, whereas active tags require a power source.
Types of RFID tags
Passive
Passive RFID tags have no internal power supply. A minute electrical current is induced in the small circuit as it is brought in the special magnetic region, generated by the tag Reader. This small power is sufficient to em-mite the response signals. Which can be traced by the Reader.

Active
Unlike passive RFID tags, active RFID tags have their own internal power source which is used to power any ICs that generate the outgoing signal. Active tags are typically much more reliable than passive tags due to the ability for active tags to conduct a “session” with a reader. They are more reliable in magnetic field ore naturally challenged region.

The RFID system
An RFID system may consist of several components: tags, tag readers, edge servers, middleware ( eg. Sun Java System RFID Software, IBM RFID Middle-ware), and enterprise application software.
The purpose of an RFID system is to enable data to be transmitted by a mobile device, called a tag, which is read by an RFID reader and processed according to the needs of a particular application. The data transmitted by the tag may provide identification or location information, or specifics about the product tagged, such as price, color, date of purchase, etc. RFID is being so popular because its ability to track moving objects. As the technology is refined, it is being used in different areas like asset tracking, transportation, inventory management, defense, health care etc. ..

 

How to develope a RFID prototype application

To develope a RFID prototype, companies like Java, IBM , sybase are we provideing their middleware . Sun has its SUN RFID 1.3 package , similarly IBM is also providing a framework to develope, test and deploy a rfis solution. IBM provides a architecture comprising Device developer kit ( will be used to develope edge controller which will controll rfid related hardware), RFID premises server which works between edge controler and your enterprise application.

feel free to ask more queries\details on RFID :
manjulx@gmail.com

 

Time is limited…so enjoy every moment :)

Time is limited…so enjoy every moment

While you will be reading this paragraph…
by that time you have spent 2 precise moments of your life which will not come back…
does not matter how much intelligent you are….does not matter how much you are earning… but you cant get those moments back..

So enjoy every single moment of this life, so that at the second inning ( at the age of 50), if you see back …to see what you have done in your life … you can see that you have spreaded smiles on 100’s of faces…

These faces will always be there with you at any stage of your life , will be with you in all ups and downs of your life.

So my dear friends  dont wast your life, enjoye it as more as you can …

Keep smiling…Keep living… 🙂

Past > Future > Present

Your Future is more dominated by your Past than your Present

You won’t believe but it is true that what you decide and wants to do in your future is dominated by your past, not present. For example suppose you make a plan to invite few people in your b-day then your past decides the people with whom you had good relations you would like to invite in future. another example suppose you wants to attend a seminar/speech your past feelings about that person dominates your mind and don’t allow you to think freely.

so try to unlink your past which is making you weak and creating restrictions on your future. think with the open mind ..always !

you will explore a new life in you !

Blog Likes

  • 24,811 Likes