Free CoreJava Programs Source codes | Examples | Video Tutorials Download

Monday, February 16, 2009

StringTokenizer Program


/**

* Write a example for StringTokenizer.

*


*

*/

public class StringTokenizer {

public void stringTokenizerDemo() {

// source string

String strSource = "Ritesh Loves India";

// delimeter string

String strDeli = "i";

System.out.println("\nSource String is : " + strSource);

System.out.println("\nExample 1:-");

System.out.println("------------");

System.out.println("\tDelimeter String is : " + strDeli);

System.out.println("\tTokens Are :");

// specify the string with delimeter string by which it would be splited

java.util.StringTokenizer st = new java.util.StringTokenizer(strSource, strDeli);

while (st.hasMoreTokens()) {

System.out.println("\t\t" + st.nextToken());

}

// another example

strDeli = " ";

System.out.println("Example 2:-");

System.out.println("------------");

System.out.println("\tDelimeter String is : " + strDeli + "");

System.out.println("\tTokens Are : ");

st = new java.util.StringTokenizer(strSource, strDeli);

while (st.hasMoreTokens())

System.out.println("\t\t" + st.nextToken());

}

/**

* execution begin from here

*

* @param args

* command line argument

*/

public static void main(String[] args) {

new StringTokenizer().stringTokenizerDemo();

}

}

Program to lists all the constructors, methods and fields of class

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

/**

* Make a class which lists all the constructors, methods and fields of the

* specified class.

*

*

*/

public class ClassPropertyTest1 {

/**

* execution begins from here

*

* @param args

* commandline arguments

*/

public static void main(String[] args) {

// get the data of MyClass

new ClassPropertyTest1().getSourceClassData();

}

/**

* gets all the data of class SourceClass

*

*/

public void getSourceClassData() {

System.out.println("SourceClass Details : ");

System.out.println("---------------------");

SourceClass srcObj = new SourceClass();

System.out.println("\tAvailable Fields Are ::");

System.out.println("\t-----------------------");

int i = 0;

for (Field fldObj : srcObj.getClass().getDeclaredFields()) {

System.out.println("\tField (" + (i++) + ") : " + fldObj);

}

System.out.println("\n\n\tAvailable Constructors Are ::");

System.out.println("\t-----------------------------");

i = 0;

for (Constructor cObj : srcObj.getClass().getDeclaredConstructors()) {

System.out.println("\tConstructor (" + (i++) + ") : " + cObj);

}

System.out.println("\n\n\tAvailable Methods Are ::");

System.out.println("\t------------------------");

i = 0;

for (Method cObj : srcObj.getClass().getDeclaredMethods()) {

System.out.println("\tMethod (" + (i++) + ") : " + cObj);

}

}

}

/**

* source class for getting data of its memebers

*

*/

class SourceClass {

// member variables

private int intVar;

private static final float PI = 3.14f;

// default constructor

SourceClass() {

intVar = 0;

}

// parameeterized constructor

SourceClass(int intV) {

intVar = intV;

}

// displays value of intVar

public void display() {

System.out.println("Value of intVar : " + intVar);

}

}

Program to List constructors with name and signatures of class

import java.lang.reflect.Constructor;

/**

* List all the constructors with name and signatures present in the specified

* class. Make separate class and method for this functionality.

*

*

*/

public class ClassPropertyTest {

/**

* execution begins from here

*

* @param args

* commandline arguments

*/

public static void main(String[] args) {

// get the data of MyClass

new ClassPropertyTest().getMyClassData();

}

/**

* fetches all the constructor data of MyClass class

*

*/

public void getMyClassData() {

System.out.println("MyClass Details : ");

System.out.println("-----------------");

MyClass mcObj = new MyClass();

System.out.println("\tAvailable Constructors Are ::");

System.out.println("\t-----------------------------\n");

int i = 0;

for (Constructor cObj : mcObj.getClass().getDeclaredConstructors()) {

System.out.println("\tConstructor (" + (i++) + ") : " + cObj);

}

}

}

/**

* source class for fetching its constructor

*

*

*/

class MyClass {

// int member variable

private int intVar;

// default constructor

MyClass() {

intVar = 0;

}

// first paraemeterized constructor

MyClass(int intV) {

intVar = intV;

}

}

Second Program for Interface Demonstration

package day7;

/**

* Write a program which illustrates how to declare interfaces and implement

* them in various classes. interfaces AntiLockBrakes,CruiseControl and

* PowerSteering declare optional functionality for an automobile. Each

* interface declares one method which has the same name as its interface. the

* abstract Auto class is extended by the Model1,Model2 and Model3 classes.

* PowerSteering is available for Model1 objects. AntiLockBrakes and

* CruiseControl are available for Model2 objects. CruiseControl is available

* for Model3 objects. Instantiate each of these classes and invoke methods

*

*

*/

/**

* base interface with AntiLockBrackes facilities

*

*/

interface AntiLockBrakes {

void AntiLockBrakes();

}

/**

* base interface with CruiseControl facilities

*

*

*/

interface CruiseControl {

void CruiseControl();

}

/**

* base interface with PowerSteering functionalities

*

*

*/

interface PowerSteering {

void PowerSteering();

}

/**

* abstract class that would be inherited

*

*

*/

abstract class Auto {

abstract public void display();

}

/**

* it implements PowerStreeing and extends Auto

*

*

*/

class Model1 extends Auto implements PowerSteering {

/**

* overrides the method of PowerSteering interface

*/

public void PowerSteering() {

System.out.println("\nDisplay from Model1:PowerSteering()!!");

}

/**

* display PowerStreeing()

*/

public void display() {

PowerSteering();

}

}

/**

* implements AntiLockBrakes, CruiseControl and extends Auto

*

*

*/

class Model2 extends Auto implements AntiLockBrakes, CruiseControl {

/**

* overrides AntiLockBrakes

*/

public void AntiLockBrakes() {

System.out.println("\nDisplay from Model2:AntiLockBrakes()!!");

}

/**

* overrides CruiseControl

*/

public void CruiseControl() {

System.out.println("\nDisplay from Model2:CruiseControl()!!");

}

/**

* displays AntiLockBrakes()

*/

public void display() {

AntiLockBrakes();

CruiseControl();

}

}

/**

* Implements cruisecontrol and extends Auto class

*

*

*/

class Model3 extends Auto implements CruiseControl {

/**

* implements CruiseControl

*/

public void CruiseControl() {

System.out.println("\nDisplay from Model3:CruiseControl()!!");

}

// displays CruiseControl

public void display() {

CruiseControl();

}

}

/**

* class where execution starts

*

*

*/

public class InterfaceTest1 {

/**

* exectuion begin from here

*

* @param args

* commandline arguemtns

*/

public static void main(String[] args) {

// create instance of classes and call methods

Model1 m1Obj = new Model1();

m1Obj.display();

Model2 m2Obj = new Model2();

m2Obj.display();

Model3 m3Obj = new Model3();

m3Obj.display();

}

}

Program for Interface Demonstration

/**

* write another prog in which interface K1 declares method named methodK()

* and a variable intK which is intialised to 1.

* interface K2 extends K1 and declares method methodK().

* interface K3 extends K2 and declares method methodK().

* the return type of methodK() is void in all interfaces.

* class U implements K3.its version of methodK() displays the value of intK.

* instantiate U and invoke its method

*

*

*/

/**

* first base interface

*/

interface K1 {

// that would be printed

int intK = 1;

// will be used to display value of intK

void methodK();

}

/**

* extends K1

*

*

*/

interface K2 extends K1 {

// overrides K1 method

void methodK();

}

/**

* extends K2

*

*

*/

interface K3 extends K2 {

// overrides K2 method

void methodK();

}

/**

* implements interface K3 and displays value of intK

*

*

*/

class U implements K3 {

/**

* displays value of intK

*/

public void methodK() {

System.out.println("Value of intK : " + intK);

}

}

/**

* a class that will be executed

*

*

*/

public class InterfaceTest {

/**

* execution begn from here

*

* @param args

* commandline arguments

*/

public static void main(String[] args) {

// create instance of U

new U().methodK();

}

}

Program of Final class, Method and Variable

/**

* Write a example of Final class, Method and Variable. Also explain the same.

*

*

*/

public final class FinalTest { // final class

// final variable

private final static float PI = 3.14f;

// final method

public final void displayPI() {

System.out.println("Final Variable : PI=3.14f : \nOnce its value is assigned, can't alter it!!");

System.out.println("\nFinal Method : displayPI() \nA method that can't be overridden by child class!!");

System.out.println("\tValue Of PI : " + PI);

System.out.println("\nFinal Class: FinalTest : \nA class that can't not be inherited!!");

}

/**

*

* execution begin from here

*

* @param args

* command line arguments

*/

public static void main(String[] args) {

new FinalTest().displayPI();

}

}

Program to calculate the Salary of the person

/**

* Make a class to calculate the Salary of the person (Employee, PL) such that,

* 1)Basics is not decided in the class, but provided by the person.

* 2)It can calculate the HRA and the salary, depending upon the Basic.

* Make two different class, One for Employee and other for PL.

* Print the Salary of each Person with Basic and HRA amounts.

* (Abstract class need to be used.)

*


*

*/

/**

* abstract parent class for salary calculation

*/

abstract class SalaryCalc {

// RATE OF HRA for employee

static final float HRA = 12;

// basic salary

float flBasic;

// calculation method

public abstract void calcSalary();

}

/**

* it extends SalaryCalc for employee salary calculation

*

* @author Ritesh

*

*/

class Employee extends SalaryCalc {

/**

* constructor for salary input

*

* @param flSal

* basic salary

*/

Employee(float flSal) {

flBasic = flSal;

}

/**

* salary calculation

*/

public void calcSalary() {

System.out.println("\tBasic Salary of Employee : " + flBasic);

System.out.println("\tHRA = " + HRA + "%");

System.out.println("\tTotal Salary : "

+ ((flBasic * (HRA / 100)) + flBasic));

}

}

/**

* PL salary calculation

*

* @author Ritesh

*

*/

class PL extends SalaryCalc {

/**

* constructor for salary of PL

*

* @param flSal

* salary input

*/

PL(int flSal) {

flBasic = flSal;

}

/**

* calculates Pl salary and return it

*/

public void calcSalary() {

System.out.println("\tBasic Salary of PL = " + flBasic);

System.out.println("\tHRA = " + HRA + "%");

System.out.println("\tTotal Salary : "

+ ((flBasic * (HRA / 100)) + flBasic));

}

}

/**

* salary calculation with HRA

*

* @author Ritesh

*

*/

public class Exercise4 {

/**

* execution begin from here

*

* @param args

* commanline arguments

*/

public static void main(String[] args) {

System.out.println("Employee Salary Calculation : ");

new Employee(10000).calcSalary();

System.out.println("\nPL Salary Calculation : ");

new PL(30000).calcSalary();

}

}

Make an Exception class InvalidInputException Program


/**

* Make an Exception class (InvalidInputException) such that 1)Anyone can set

* the message explicitly. 2)With every message, there should be a text like

* "[Name of class]" This Exception will be thrown if user enters the age below

* 1 or above 155 Make another class to use this exception Test this Class and

* observe the output.

*


*

*/

public class InvalidInputException extends Exception {

/**

* constructor with default message

*/

public InvalidInputException() {

super("Invalid Input Exception Generated!!");

}

/**

* constructor with custom message

*

* @param msg

* custom message

*/

public InvalidInputException(String msg) {

super(msg);

}

/**

* execution begin from here

*

* @param args

* commandline arguments

*/

public static void main(String[] args) {

CreateException ce = new CreateException(0);

ce.checkInvalidInputException();

}

}

/**

* Used to check InvalidInputException

*

* @author Ritesh

*

*/

class CreateException {

// age that is the measure

private int age;

/**

* constructor

*

* @param age

* initialization parameter

*/

public CreateException(int age) {

this.age = age;

}

/**

* checks for valid input else throw InvalidInputException

*

*/

public void checkInvalidInputException() {

try {

// checks age range

if (age <> 155) // if not valid age

throw new InvalidInputException(

"In Class : "

+ getClass().getName()

+ " : Invalid age entered : age should be >1 and <155!!");

else { // valid age

System.out.println("Age : " + age);

System.out.println("Valid age Entered!!!");

}

} catch (InvalidInputException iie) {

iie.printStackTrace();

}

}

}

Print private variable of Parent class from child class Program

/**

* Write a Parent and child class. Parent class has one private variable called

* x. Please print value of x from child class.

*

*

*/

public class Modifier {

/**

* execution begin from here

*

* @param args

* commandline arguments

*/

public static void main(String[] args) {

// create child class object and display X

Child chObj = new Child(6);

chObj.displayX();

}

}

/**

* Parent class which will be inherited by Child to display x

*

* @author Ritesh

*

*/

class Parent {

// x that will be fetched

private int x;

/**

* Constructor

*

* @param x

* initialization parameters

*/

Parent(int x) {

setX(x);

}

/**

* get value of x

*

* @return x

*/

public int getX() {

return x;

}

/**

* sets value of x

*

* @param x

* argument for x

*/

public void setX(int x) {

this.x = x;

}

}

/**

* Inherits Parent class members and display value of x

*

* @author Ritesh

*

*/

class Child extends Parent {

/**

* child class constructor

*

* @param x

* initialization parameter

*/

Child(int x) {

super(x);

}

/**

* displays value of x

*

*/

public void displayX() {

System.out.println("Parent.x = " + getX());

}

}

Sunday, February 8, 2009

When A Synchronized Class Isn’t Threadsafe

Every Java programmer has heard this advice before: “Prefer ArrayList over Vector. Vector is fully synchronized, and as such you’re paying the synchronization penalty even when you don’t need it.”

ArrayList is not synchronized, so when you need it you need to perform synchronization yourself, or alternatively, as the ArrayList javadoc entry says: “… the list should be “wrapped” using the Collections.synchronizedList method.” Something like this:

  1. List list = Collections.synchronizedList(new ArrayList());

The resulting List will be synchronized, and therefore can be considered safe.
Or is it?

Not really. Consider the very contrived example below.

  1. final List list = Collections.synchronizedList(new ArrayList());
  2. final int nThreads = 1;
  3. ExecutorService es = Executors.newFixedThreadPool(nThreads);
  4. for (int i = 0; i <>
  5. es.execute(new Runnable() {
  6. public void run() {
  7. while(true) {
  8. try {
  9. list.clear();
  10. list.add("888");
  11. list.remove(0);
  12. } catch(IndexOutOfBoundsException ioobe) {
  13. ioobe.printStackTrace();
  14. }
  15. }
  16. }
  17. });
  18. }

As long nThreads is 1, everything runs just fine. However, increase the number of nThreads to 2, and you start getting this:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

at java.util.ArrayList.RangeCheck(Unknown Source)

at java.util.ArrayList.remove(Unknown Source)

at java.util.Collections$SynchronizedList.remove(Unknown Source)

Changing the synchronized List to Vector doesn’t help either. What happened here? Well, individual method calls of synchronized List and Vector are synchronized. But list.add() and list.remove() can be called in any order between the 2 threads. So if you print list.size() after list.add(), the output is not always 1. Sometimes it’s 0, sometimes it’s 2. Likewise, thread 1 may call list.add(), but before it gets a chance to call list.remove(), thread 2 gets into action and calls list.clear(). Boom, you get IndexOutOfBoundsException.

In that example above, the 3 calls to List’s methods have to be atomic. They must happen together as one unit, no interference from other threads, or else we’ll get the IndexOutOfBoundsException again. The fact that the individual methods are synchronized is irrelevant. In fact, we can go back to using the non-synchronized ArrayList, and the program will work, as long as we synchronize properly to make the 3 calls happen as one atomic, indivisible unit of execution:

  1. synchronized (list) {
  2. list.clear();
  3. list.add("888");
  4. list.remove(0);
  5. }

The moral of the story is that just because a class is fully synchronized, doesn’t mean it’s threadsafe (UPDATE: as in doesn’t mean your code will be threadsafe from using it–thanks Alex). You still have to be on the look for those sequence of method calls that have to occur atomically, because method level synchronization won’t help in this regard. In other words, watch what you’re doing. (And yes, we should still prefer ArrayList over Vector.)

Threadsafe Iteration & ConcurrentModificationException

Sometimes it’s not so obvious when exactly we’re supposed to synchronize our use of Collections. Ever encountered a ConcurrentModificationException before? I bet it’s probably because your code looks something like this (a.k.a.: why the for-each loop isn’t such a great idea actually):

  1. final List list = new ArrayList();
  2. list.add("Test1");
  3. list.add("Test2");
  4. list.add("Test3");
  5. for(String s : list) {
  6. if(s.equals("Test1")) {
  7. list.remove(s);
  8. }
  9. }

ConcurrentModificationException will be thrown in this case, even when there’s only a single thread running. To fix this problem, we can’t use the for-each loop since we have to use the remove() method of the iterator, which is not accessible within the for-each loop. Instead we have to do this:

  1. for(Iterator iter = list.iterator(); iter.hasNext();) {
  2. String s = iter.next();
  3. if(s.equals("Test1")) {
  4. iter.remove();
  5. }
  6. }

The point is that iteration is something that we’d probably want to happen atomically–that is, while we’re iterating over a collection, we don’t want other threads to be modifying that collection. If it happens most probably something is wrong with our design.

This is why if you look into the JDK source code, the implementation for Iterator usually checks the expected modification count (i.e.: how many times is this collection supposed to have been modified?) against the collection’s current modification count (how many times this collection has been modified). If they don’t tally, the Iterator assumes that another thread has modified the collection while the iteration is going on, so it throws the ConcurrentModificationException. (This is exactly what happens in our single-threaded case about too by the way–the call list.remove() increases the modification count such that it no longer tallies with the one that the iterator holds (whereas iter.remove() resets the mod count so they still tally.) ConcurrentModificationException is a useful exception–it informs us of a probable fault in our design.

When Volatile Fails

However, ConcurrentModificationException is not 100% reliable. The implementation of Iterator.next() may look something like this:

  1. public E next() {
  2. if (modCount != expectedModCount)
  3. throw new ConcurrentModificationException();
  4. // other stuff

That is, ConcurrentModificationException is supposed to be thrown when the mod counts don’t tally. But it may not get thrown because the thread on which the modCount check is running is seeing a stale value of modCount. That is, let’s say you have thread A iterating through a collection. Whenever you call iter.next(), it checks that modCount == expectedModCount. But modCount may have been modified by thread B, and yet A is still seeing the unmodified value. If you remember, this is what the volatile keyword is about–it is to guarantee that a thread will always see the most recent value of a variable marked as such.

So why didn’t Joshua Bloch (or whoever took his place in Sun to take care of the Collections API) mark the modCount volatile? That would at least make the concurrent modification detection mechanism more reliable, yes? Well… no. Actually marking modCount volatile won’t help, because although volatile guarantees uptodateness, it doesn’t guarantee atomicity.

What does that mean? Well, if you examine the implementation of ArrayList, you’ll see that methods that modify the list increment the modCount (non-volatile) variable by one (i.e.: modCount++). So theoretically, if we mark modCount as volatile, whenever thread B says modCount++, thread A should always immediately see the value and throws ConcurrentModificationException.

But there is a problem: the increment operator (++) is not atomic. It is actually a compound read-modify-write sequence. So while thread B is in the middle of executing modCount++, it’s entirely possible that the thread scheduler will kick thread B out and decide to run thread A, which then checks for modCount before B has a chance to write back the new value of modCount.

Hidden Iteration

As if things aren’t hairy enough as they are, it’s not always obvious when an iteration over a collection is happening. Sure, it’s probably pretty easy to spot iteration code we’ve written ourselves, so we can synchronize those. However, much less obvious are the iterations that happen within the harmless-looking methods of the Collections API. If you examine the source code of java.util.AbstractCollection class, for example, you’ll see that methods like contains(), containsAll(), addAll(), removeAll(), retainAll(), clear()… practically almost all of them trigger an iteration over the collection. Iteration suddenly becomes a LOT harder to spot!

So What Do We Do?

Sounds pretty hopeless, isn’t it? Well… nah. A very, very smart CS professor named Doug Lea has figured it out for the rest of us. He came up with concurrent collection classes, which handle the problems listed above for the most common cases. These concurrent collections have been part of the standard Java API in java.util.concurrent package. For most cases, they are drop-in replacement for the corresponding non-threadsafe classes in java.util package, and if you haven’t taken a good look at them, it’s time that you do!

Followers