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

Sunday, April 22, 2012

A short and simple explanation about Threads in java

Multi-tasking :  it involves having multiple process (playing music and using text editor) -- Heavy weight

Multi-threading: it involves having mulitple threads(in text editor editing and printing) -- Light Weight

Creating a thread
- Runnable Interface
- Thread Class

- Using Runnable Interface

    Extend Runnable interface and use run method in it.

ex :


class B
{
       PSVM()
     {
          A a_ref= new A();
         a_ref.UseThread();
    }
}





  class A implements Runnable
{

    public void UseThread()
      {
              Thread new_thread = Thread(this, "new thread");
                 new_thread.start();
       }
       private void run()
      {
                // some code
      }
}



- Using Thread Class


  class A extends Thread
{

    public void UseThread()
      {
                 start();
       }
       private void run()
      {
                // some code
      }
}



// its better to implement runnable





Multiple Threads




class B
{
       PSVM()
     {
          A a_ref= new A();
         a_ref.UseThread("one");
             a_ref.UseThread("two");
         a_ref.UseThread("three");

    }
}





  class A implements Runnable
{

    public void UseThread(String threadname)
      {
              Thread new_thread = Thread(this, threadname);
                 new_thread.start();
       }
       private void run()
      {
                // some code
      }
}



using isalive and join methods


// Using join() to wait for threads to finish.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}






Do synchronize with  synchronized keyword or use synchrnoized(object) {  // some code }








Friday, March 23, 2012

xml parser

writing a parser to read xml data.

 Below is a simple script for reading data from any xml file. all you need to know is send a xml file and reading output data from a hashmap.





ParserActivity.java


package com.example.parsers;
import java.net.URL;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ParserActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url_value = "   ";
try {
URL url = new URL(url_value);
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();

HandlerData handler = new HandlerData();
sp.parse(new InputSource(url.openStream()), handler);

getData outdata = handler.getParseddata();
HashMap<String, String> finalhash = new HashMap<String, String>();
finalhash = outdata.gethashdata();

TextView txt = (TextView) findViewById(R.id.text);
txt.setText("abcd");
} catch (Exception e) {
// TODO Auto-generated catch block

}

}
}








HandlerData.java



package com.example.parsers;

import java.util.ArrayList;
import java.util.HashMap;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

class HandlerData extends DefaultHandler {

getData data = new getData();

public getData getParseddata() {
return this.data;
}

HashMap<String, String> outcontent = new HashMap<String, String>();

HashMap<String, Boolean> ischeck = new HashMap<String, Boolean>();
String temp = null;

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
String middle_content = new String(ch, start, length);

if (ischeck.get(temp)) {
outcontent.put(temp, middle_content);
ischeck.put(temp, false);
}

}

@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
data.sethashdata(outcontent);
ArrayList<String> keys= new ArrayList<String>(outcontent.keySet());
for(String key : keys)
{
Log.w("outputdata",key+"-"+outcontent.get(key));
}


}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
}

@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
int total_attributes = attributes.getLength();
if (total_attributes > 0) {
while (total_attributes > 0) {
total_attributes--;
String att = "" + attributes.getQName(total_attributes);
String value = attributes.getValue(att);
outcontent.put(att, value);
}
}
ischeck.put(qName, true);
temp = qName;
}

}








getData.java


package com.example.parsers;

import java.util.HashMap;

public class getData {

HashMap<String, String> content = new HashMap<String, String>();

public void sethashdata(HashMap<String, String> input) {
this.content = input;

}

public HashMap<String, String> gethashdata() {
return content;
}
}








Monday, November 7, 2011

close file handler in java while operating on files

I just bumped into one of the error with file io. if you dont close fie handler, it wont write anything into file.
import java.io.*;
class FileWrite 
{
 public static void main(String args[])
  {
  try{
  // Create file 
  FileWriter fstream = new FileWriter("out.txt");
  BufferedWriter out = new BufferedWriter(fstream);
  out.write("Hello Java");
  //Close the output stream
  out.close();
  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

executing external process using java

Runtime rt=Runtime.getRuntime();
  Process x= rt.exec("ls -l");
  BufferedReader stdInput = new BufferedReader(new 
                InputStreamReader(x.getInputStream()));
  String s;
  while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

Adding new elements to arraylist in java while using iterator

today i had a problem with usage of arraylist along side of iterator. the problem was that i was unable to add elements to the arraylist. it gives you an error java.util.ConcurrentModificationException this is because u cant add elements to an arraylist while using an iterator. so i had used listiterator as below.

import java.util.ArrayList;
import java.util.ListIterator;
public class Test 
{
 public static void main(String args[])
 {
  ArrayList array_test= new ArrayList();
  array_test.add("a");
  array_test.add("k");
  array_test.add("d");
  array_test.add("s");
  array_test.remove("d");
  int i=1;
  for(ListIterator it=array_test.listIterator();it.hasNext();)
  { 
   String link=it.next(); 
   if(i==1)
   {  
    it.add("r");
    it.previous();
    it.add("kk");
    it.previous();
   i++;
   }
   System.out.println(link);
   
  } 
   
  System.out.println("Contents of arrays list "+array_test);
 }
 

}

In the above code i had used it.previous whenever i used it.add. this is because i want to use the added value in the loop again. while the addition of new element in array is added just before next element in arraylist.

Wednesday, September 28, 2011

collections in java
array list algorithm (dynamic array)
map
hashmap ( unordered data)
linkedhashmap ( ordered data)
- treemap are type of linked hash map better in implementation
java iterators for getting next element link
mutable and imutable onbjects link

Monday, November 22, 2010

java stuff...

java blocking queue...
producer and consumer..

java threads...java concurrent
java.util.concurrent.atomic

java cubbyhole

java collections
java pattern matching
java map
hash map

java hotspot

scala programming

Monday, October 18, 2010

installing Java

i know many of us get struck with the little things... the code below are few simple steps to install java on your machine

Linux
-----
Add partner repository using the following command

> sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"

Update the source list

> sudo apt-get update

Now install sun java packages using the following commands

> sudo apt-get install sun-java6-jre sun-java6-plugin sun-java6-fonts


test by using the following command

java -verison





Just installing new Java flavours does not change the default Java pointed to by /usr/bin/java. You must explicitly set this:

Open a Terminal window
Run sudo update-java-alternatives -l to see the current configuration and possibilities.
Run sudo update-java-alternatives -s XXXX to set the XXX java version as default. For Sun Java 6 this would be sudo update-java-alternatives -s java-6-sun
Run java -version to ensure that the correct version is being called.
You can also use the following command to interactively make the change;

Open a Terminal window
Run sudo update-alternatives --config java
Follow the onscreen prompt
You can also try IcedTea NPR Web Browser Plugin

Thursday, August 26, 2010

setting java path

goto nano ~/.bashrc file


JAVA_HOME=/usr/java/jdk1.6.0_21
export JAVA_HOME
PATH=$PATH:/usr/java/jdk1.6.0_21/bin
export PATH
PATH=$PATH:/usr/share/maven2/bin
export PATH
ANT_HOME=/usr/share/ant
PATH=$PATH:${ANT_HOME}/bin
export PATH