Search This Blog

Tuesday 19 August 2014

Restrict access to Shared Data - Thread Synchronization - JAVA

How to Restrict access to shared data one thread at a time in Java - Thread Synchronization

When a data is being shared among different threads, we need to restrict the access of one thread at a time to avoid race conditions.


This program shows how to Restrict access to a shared data among different threads in Java by using thread synchronization..

ThreadCreationJava.java

public class Main {
 public static void main(String args[]){
  TargetClass target = new TargetClass();
  MyThread t1 = new MyThread(1,target); //thread id , shared object
  MyThread t2 = new MyThread(2, target);
  MyThread t3 = new MyThread(3, target);
  
  t1.start();
  t2.start();
  t3.start();
 }
}

MyThread.java

public class MyThread extends Thread {
 private int threadId;
 private TargetClass target;
 
 public MyThread(int i, TargetClass target2) {
  threadId = i; target = target2;
 }

 @Override
 public void run() {
  
  synchronized (target) { // we place shared data here. Now only one thread can access shared data at a time.
   
   try {
    sleep(2000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   target.call(threadId);
  }
  
 }
}

TargetClass.java

public class TargetClass {
 
 public void call(int threadId){
  System.out.println("Function called from thread " + threadId);
 }
 
}

Monday 18 August 2014

How to Interrupt Thread - JAVA

How to Interrupt Thread in Java

When you run a secondary thread, it will run to completion or till an exception occurs or you explicitly interrupted from the process that created it.


This program shows how to Interrupt Thread in Java..

InterruptThreadJava.java

public class InterruptThreadJava {
 public static void main(String args[]){
  MyThread thread = new MyThread();
  thread.start();
  //stop thread after 2 iterations
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  thread.interrupt();
  System.out.println("Iterrupt called");
 }
}

MyThread.java

public class MyThread extends Thread {
 @Override
 public void run() {
  int iterator = 5;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 2nd Thread:  i = " + i);
    sleep(1000);
   }
  } catch (InterruptedException e) {
   System.out.println("Thread interrupted");
  }
 }
}

Thread Creation - Implementing Runnable Interface

How to Create Threads in Java - Implement the runnable interface

Threads are used to achieve concurrency meaning running multiple tasks at the same time. One way to use threads in Java is to implement runnable interface and the other is to extend the thread class. In this chapter, We'll learn how to implement runnable interface to implemnet multi-threading in Java.

Which of these idioms should you use? The first idiom (implementing the runnable interface), which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom (extending the thread class) is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.

This program shows how to use Threads in Java by implementing the runnable interface..

ThreadCreationJava.java

public class ThreadCreationJava {
 public static void main(String args[]){
  MyThread thread = new MyThread();
  thread.start();
  RunnableInterfaceClass runnableInterfaceObject = new RunnableInterfaceClass();
  new Thread(runnableInterfaceObject).run();
  
  int iterator = 3;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 1st Thread:  i = " + i);
    Thread.sleep(3000);
   }
  } catch (InterruptedException e) {
   System.err.println(e);
  }
 }
}

MyThread.java

public class MyThread extends Thread {
 @Override
 public void run() {
  int iterator = 5;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 2nd Thread:  i = " + i);
    sleep(2000);
   }
  } catch (InterruptedException e) {
   System.err.println(e);
  }
 }
}

RunnableInterfaceClass.java

public class RunnableInterfaceClass implements Runnable {

 @Override
 public void run() {
  int iterator = 5;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 3rd Thread:  i = " + i);
    Thread.sleep(2000);
   }
  } catch (InterruptedException e) {
   System.err.println(e);
  }
 }

}

Saturday 16 August 2014

How to Create Threads in Java - Extending the Thread Class

How to Create Threads in Java - Extending the Thread Class

Threads are used to achieve concurrency meaning running multiple tasks at the same time. One way to use threads in Java is to implement runnable interface and the other is to extend the thread class. We'll learn how to extend the thread class to implement multi-threading in Java.

Which of these idioms should you use? The first idiom (implementing the runnable interface), which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom (extending the thread class) is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.


This program shows how to use Threads in Java by extending the thread class..

ThreadCreationJava.java

public class ThreadCreationJava {
 public static void main(String args[]){
  MyThread thread = new MyThread();
  thread.start();
  
  int iterator = 3;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 1st Thread:  i = " + i);
    Thread.sleep(3000);
   }
  } catch (InterruptedException e) {
   System.err.println(e);
  }
 }
}

MyThread.java

public class MyThread extends Thread {
 @Override
 public void run() {
  int iterator = 5;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 2nd Thread:  i = " + i);
    sleep(2000);
   }
  } catch (InterruptedException e) {
   System.err.println(e);
  }
 }
}

Defining and throwing Custom Exceptions - JAVA

Defining and throwing Custom Exceptions in Java

In Java you can define and throw your own exceptions by creating your own exception classes.


This program shows how to create and use, define and throw Custom Exceptions in Java.

CustomExceptions.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import CustomExceptions.MyCustomExceptionClass;

public class CustomExceptions {
 public static void main(String args[]){
  FileReader fr = null;
  BufferedReader br = null;
  try {
   fr = new FileReader("myFile.txt");
   br = new BufferedReader(fr);
   String line;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
   if (line != "my Desired output or some other condition")
    throw(new MyCustomExceptionClass());
   
  } catch (MyCustomExceptionClass e) {
   e.getMessage();
  }
    catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  finally{ //close
   System.out.println("Executing finally ...");
   if (fr != null){
    try {
     fr.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
  System.out.println("Still Alive!");
 }
}

MyCustomExceptionClass.java

package CustomExceptions;

public class MyCustomExceptionClass extends Exception {

 /**
  * Every Exception class must have this serialVersionUID.
  * Assuming 45 means some code to me.
  */
 private static final long serialVersionUID = 45; 
 
 @Override
 public String getMessage() {
  return "My Custom Exception Class is printing this message showing the problem";
 }
}

Friday 15 August 2014

Finally - JAVA

Finally in Java

After try catch block another block called finally is added. This block runs regardless of exception is thrown or not. Therefore this block is usually used from clean up purposes.


This program shows how to use Finally keyword in Java.

Finally.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Finally {
 public static void main(String args[]){
  FileReader fr = null;
  BufferedReader br = null;
  try {
   fr = new FileReader("myFile.txt");
   br = new BufferedReader(fr);
   String line;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally{ //close
   System.out.println("Executing finally ...");
   if (fr != null){
    try {
     fr.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
  System.out.println("Still Alive!");
 }
}

Thursday 14 August 2014

Assert - JAVA

Assert in Java

Assert is a reserved keyword not a method. It checks if the condition after it is true the application continues successfully otherwise vice versa.


This program shows how to use Assert in Java.

Assert.java

import javax.swing.JOptionPane;

public class Assert {
 public static void main(String args[]){
  //Get input
  String numeric = JOptionPane.showInputDialog("Enter a numeric value: ");
  //Check if the input is correct?
  assert checkInput(numeric); //assert true allows application to continue successfully and assert false throws an exception.
  System.out.println("You did pass a numeric value");
 }

 private static boolean checkInput(String numeric) {
  try {
   Integer.parseInt(numeric);
   return true;
  } catch (Exception e) {
   return false;
  }

 }
}


Note: You must add '-ea' argument in the command before running it to enable assert, otherwise assert won't work.

Queue - JAVA

Queue in Java

Queue is First in First out. Item inserted first comes out first when removed like a queue.



This program shows how to use Queue in Java.

Queue.java

import java.util.LinkedList;

public class MainClass {
 public static void main(String args[]){
  LinkedList linkedList = new LinkedList();
  linkedList.add("Item 1");
  linkedList.add("Item 2");
  linkedList.add("Item 3");
  System.out.println(linkedList); //Items are added in FIFO.
  
  linkedList.remove();
  System.out.println(linkedList); // First inserted has taken out first
  
  //Simply get without removing from queue
  String item = linkedList.element();
  System.out.println("Item at top: " + item);
 }
}

Linked List - JAVA

Linked List in Java

Array List is faster than Linked List but you can only add at the end in the array list. Linked List allows you to add anywhere in the list.


This program shows how to use Linked List in Java.

LinkedList.java

import java.util.LinkedList;

public class MainClass {
 public static void main(String args[]){
  LinkedList linkedList = new LinkedList();
  linkedList.add("Item 1");
  linkedList.add("Item 2");
  System.out.println(linkedList);
  
  //I want to add an item in between item 1 and item 2
  System.out.println("Adding Item in between item 1 & item 2");
  linkedList.add(1, "Item 1.5"); //at index 1
  System.out.println(linkedList);
 }
}

Tree Set - JAVA

Tree Set in Java

Tree set does everything a hash set does. To know what hash set does kindly see brief description of hash set.Though hash set is faster than Tree set but Tree Set allows you to store objects alphabetically. It does sort alphabetically automatically when you add, remove or organize your objects.

This program shows how to use Tree Set in Java.

Shape.java

import java.util.TreeSet;

public class Shape implements Comparable{
 
 public Shape() {
  
 }
 
 public Shape(String string) {
  this.name = string;
 }
 
 protected String name;

 public static void main(String[] args){
  Shape obj1 = new Shape("Shape");
  Shape obj2 = new Circle("Circle");
  Shape obj3 = new Triangle("Triangle");
  
  TreeSet treeSet = new TreeSet();
  //add first object to the hash set
  treeSet.add(obj1);
  treeSet.add(obj2);
  treeSet.add(obj3);
  System.out.println(treeSet);
  System.out.println("So you can see that the tree set is alphabetic.");
 }

 public int compareTo(Shape arg0) {
  String s1 = this.name;
  String s2 = arg0.name;
  return s1.compareTo(s2);
 }
 
 @Override
 public String toString() {
  return this.name;
 }
}

Circle.java

//Circle class inherits from Shape Class
public class Circle extends Shape{

 public Circle(String string) {
  this.name = string;
 }
 
}

Triangle.java

//Triangle Class inherits from Shape Class
public class Triangle extends Shape {

 public Triangle(String string) {
  this.name = string;
 }
 
}

Hash Set - JAVA

Hash Set in Java

Hash Set is used when simply complex objects are to be referenced in a set and when no more than only one reference to an object is needed. Hash sets are the highest performance and the simplest of the set implementations.

This program shows how to use Hash Set in Java.

Shape.java

import java.util.HashSet;

public class Shape {
 
 public static void main(String[] args){
  Shape obj1 = new Shape();
  Shape obj2 = new Circle();
  Shape obj3 = new Triangle();
  
  HashSet hashSet = new HashSet();
  //add first object to the hash set
  hashSet.add(obj1);
  System.out.println("The size of hash set is: " + hashSet.size());
  //add another object to the hash set
  hashSet.add(obj2);
  System.out.println("The size of hash set is: " + hashSet.size());
  //add another object to the hash set
  hashSet.add(obj3);
  System.out.println("The size of hash set is: " + hashSet.size());
  //Try adding already added object. It fails without giving error.
  hashSet.add(obj2);
  System.out.println("The size of hash set is: " + hashSet.size());
  //Remove one object.
  hashSet.remove(obj1);
  System.out.println("The size of hash set is: " + hashSet.size());
 }
}

Circle.java

//Circle class inherits from Shape Class
public class Circle extends Shape{
 
}

Triangle.java

//Triangle Class inherits from Shape Class
public class Triangle extends Shape {

}

Get Super Class Name - JAVA

This program shows how to Get Super Class Name in Java.

Circle.java

/**
 * Circle Inherits from Shape
 *
 */
public class Circle extends Shape{
 
}

Shape.java

public class Shape {
 
 public static void main(String[] args){
  Object obj = new Circle();
  
  Class c = obj.getClass();
  
  System.out.println("Class name = " + c.getName()); //Circle
  System.out.println("Super Class = " + c.getSuperclass()); //Shape
  System.out.println("Super's super class = " + c.getSuperclass().getSuperclass()); //Object
 }
}

Get Constructor of a class you don't know about and Call it - JAVA

This program shows how to Get Constructor of a class you don't know about and Call it in Java.

AnotherClass.java

public class AnotherClass {
 
 public AnotherClass(int no) {
  x = no;
  System.out.println("Constructor of Another Class called and the value of x is " + x);
 }
 
 public int x;

 public int getX() {
  return x;
 }
}

MainClass.java

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Get Class name in Java - Reflection API
 *
 * How to get class name when you don't know what the class is in Java
 */
public class MainClass {
 
 public static void main(String[] args){
  AnotherClass obj = new AnotherClass(1); // setting value of x = 1
  
  Class c = obj.getClass();
  
  Constructor[] constructorArray = c.getConstructors(); // Returns array of all constructors of AnotherClass
  System.out.println("Constructors of " + c.getName() + " class are " + constructorArray.length);
  //Get the constructor from the constructorArray
  Constructor constructor = constructorArray[0];
  //since we don't know about the data type of obj so we'll create an object's object
  Object object = null;
  try {
          //Invoke Constructor
object = constructor.newInstance(10);
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  }
 }
}

Get Class name in Java using Reflection API - JAVA

This program shows how to Get Class name of a class you don't know about using reflection API in Java.

AnotherClass.java

public class AnotherClass {
 public int x;

 public int getX() {
  return x;
 }
}

MainClass.java

/**
 * Get Class name in Java - Reflection API
 *
 * How to get class name when you don't know what the class is in Java
 */
public class MainClass {
 
 public static void main(String[] args){
  AnotherClass obj = new AnotherClass();
  
  Class c = obj.getClass();
  System.out.println(c.getName()); //Complete Class name
  System.out.println(c.getSimpleName()); // Class name, i.e. AnotherClass
 }
}

Wednesday 13 August 2014

This program shows how to use Enum in Java.

Enum.java

public enum Enum {// name can be other than 'Enum'
 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

MainClass.java

/**
 * How to use Enumeration in Java
 *
 * Enum in Java
 */
public class MainClass {
 
 public static void main(String[] args){
  System.out.println("Enum in java can be used in this way");
  System.out.println(Enum.FRIDAY);
  System.out.println(Enum.SATURDAY);
 }
}

Local Inner Class - Java

/**
 * How to create and use Local Inner Class in Java
 *
 * Local inner Classes have a block scope and are accessible within the block in which they're declared
 */
public class MainClass {

public static void main(String[] args){
class testing{
public void test(){
System.out.println("local inner class's method called");
}
}
new testing().test();
}
}

Anonymous Inner Class in Java

/**
 *
 * Anonymous inner classes are defined and used once within a code block in java.
 */
public class MainClass {

public static void main(String[] args){
new Object(){ // name of the class from which new class will be extended. Object is super-dooper class of all classes.
public void testing(){
System.out.println("HI");
}
} .testing();
}
}

Initialize Static Class Object - JAVA

This program shows how to initialize static object of a complex type (not primitive) in Java.

AnotherClass.java

public class AnotherClass {
 public int x;

 public int getX() {
  return x;
 }
}

MainClass.java

public class MainClass {
 
 public static AnotherClass ac;
 
 static{
  System.out.println("static ...");
  ac = new AnotherClass();
  ac.x = 3;
 }
 
 public static void main(String[] args){
  System.out.println(ac.getX());
 }
}

Generate Random Number - JAVA

import java.util.Random;

/**
 * How to generate Random numbers in Java
 *
 */
public class MainClass {
public static void main(String[] args){
Random random = new Random();
int randomNo = random.nextInt();
System.out.println("Random number is: " + randomNo);

int randomNo2 = random.nextInt(5);
System.out.println("Random number generated between 0 and 4 is: " + randomNo2);
}
}

Retrieve XML from web - JAVA

//Retrieve XML from web

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class MainClass {
public static void main(String[] args){
try {
URL url = new URL("http://www.services.explorecalifornia.org/rss/tours.php"); //Go and see what is on this link in internet explorer. It's an xml file.
StringBuilder sb = new StringBuilder();
InputStream is = url.openStream();
int c;
while (true){
if ((c = is.read()) == -1){
break;
}
else{
sb.append((char)c);
}
}
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Parse XML - JAVA

//Parse XML from web - Java program

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class MainClass {
public static void main(String[] args){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse("http://www.services.explorecalifornia.org/rss/tours.php");
NodeList nodeList = d.getElementsByTagName("title");
System.out.println("We got " + nodeList.getLength() + " elements");
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


You may also want to see: