Saturday, January 30, 2016

Topic 34: Annotations (Metadata) in Java

  • We can embed supplemental information into a source file. This information, called an annotation( or metadata), does not change the actions of a program. However, this information can be used by various tools during both development and deployment. For example, an annotation might be processed by a source-code generator.

  • An annotation is created through a mechanism based on the interface. Let’s begin with an example. Here is the declaration for an annotation called MyAnno:

// A simple annotation type.
@interface MyAnno
{
String str();
int val();
}

First, notice the @ that precedes the keyword interface. This tells the compiler that an annotation type is being declared. Next, notice the two members str( ) and val( ). All annotations consist solely of method declarations without body. Java implements these methods. Moreover, the methods act much like fields.

  • An annotation cannot include an extends clause. However, all annotation types automatically extend the Annotation interface. Thus, Annotation is a super-interface of all annotations. It is declared within the java.lang.annotation package. It overrides hashCode( ), equals( ), and toString( ), which are defined by Object. It also specifies annotationType( ), which returns a Class object that represents the invoking annotation.

  • Any type of declaration can have an annotation associated with it. For example, classes, methods, fields, parameters, and enum constants can be annotated. Even an annotation can be annotated. In all cases, the annotation precedes the declaration.

  • When we apply an annotation, we give values to its members. For example, here is an example of MyAnno being applied to a method:

// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth() { // ...

Look closely at the annotation syntax. The name of the annotation, preceded by an @, is followed by a parenthesized list of member initializations. To give a member a value, that member’s name is assigned a value. Therefore, in the example, the string “Annotation Example” is assigned to the str member of MyAnno. Notice that no parentheses follow str in this assignment. When an annotation member is given a value, only its name is used. Thus, annotation members look like fields in this context.

  • A retention policy determines at what point an annotation is discarded. Java defines three such policies, which are encapsulated within the java.lang.annotation.RetentionPolicy enumeration. They are SOURCE, CLASS, and RUNTIME.

  • An annotation with a retention policy of SOURCE is retained only in the source file and is discarded during compilation.

  • An annotation with a retention policy of CLASS is stored in the .class file during compilation. However, it is not available through the JVM during run time.

  • An annotation with a retention policy of RUNTIME is stored in the .class file during compilation and is available through the JVM during run time. Thus, RUNTIME retention offers the greatest annotation persistence.

A retention policy is specified for an annotation by using one of Java’s built-in annotations: @Retention. Its general form is shown here:

@Retention(retention-policy)

Here, retention-policy must be one of the enumeration constants. If no retention policy is specified for an annotation, then the default policy of CLASS is used.


The following version of MyAnno uses @Retention to specify the RUNTIME retention policy. Thus, MyAnno will be available to the JVM during program execution.

@Retention(RetentionPolicy.RUNTIME)

@interface MyAnno
{
String str();
int val();
}

  • Although annotations are designed mostly for use by other development or deployment tools, if they specify a retention policy of RUNTIME, then they can be queried at run time by any Java program through the use of reflection. Reflection is the feature that enables information about a class to be obtained at run time. The reflection API is contained in the java.lang.reflect package.

    • The first step to using reflection is to obtain a Class object that represents the class whose annotations we want to obtain. (Class is one of Java’s built-in classes and is defined in java.lang. There are various ways to obtain a Class object. One of the easiest is to call getClass( ), which is a method defined by Object. Its general form is shown here: 

    final Class getClass( ) //It returns the Class object that represents the invoking object.

    • After we have obtained a Class object, we can use its methods to obtain information about the various items declared by the class, including its annotations. If we want to obtain the annotations associated with a specific item declared within a class, we  must first obtain an object that represents that item. For example, Class supplies (among others) the getMethod( ), getField( ), and getConstructor( ) methods, which obtain information about a method, field, and constructor, respectively. These methods return objects of type Method, Field, and Constructor.

An example that obtains the annotations associated with a method. First obtain a Class object that represents the class, and then call getMethod( ) on that Class object, specifying the name of the method. getMethod( ) has this general form:


Method getMethod(String methName, Class ... paramTypes)

The name of the method is passed in methName. If the method has arguments, then Class objects representing those types must also be specified by paramTypes. Notice that paramTypes is a varargs parameter. getMethod( ) returns a Method object that represents the method. If the method can’t be found, NoSuchMethodException is thrown.

From a Class, Method, Field, or Constructor object, we can obtain a specific annotation associated with that object by calling getAnnotation( ). Its general form is shown here:

Annotation getAnnotation(Class annoType)

Here, annoType is a Class object that represents the annotation in which we are interested. The method returns a reference to the annotation. Using this reference, we can obtain the values associated with the annotation’s members. The method returns null if the annotation is not found, which will be the case if the annotation does not have RUNTIME retention.

Here is a program that assembles all of the pieces shown earlier and uses reflection to display the annotation associated with a method.

import java.lang.annotation.*;
import java.lang.reflect.*;

// An annotation type declaration.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno
{
String str();
int val();
}

class Meta {
// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth()
{
Meta ob = new Meta();
// Obtain the annotation for this method and display the values of the members.
try {
// First, get a Class object that represents this class.
Class c = ob.getClass();
// Now, get a Method object that represents this method.
Method m = c.getMethod("myMeth");
// Next, get the annotation for this class.
MyAnno anno = m.getAnnotation(MyAnno.class);

// Finally, display the values.
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}

The output from the program is shown here: Annotation Example 100

In the program, the expression MyAnno.class evaluates to a Class object of type MyAnno, the annotation. This construct is called a class literal. We can use this type of expression whenever a Class object of a known class is needed. For example, this statement could have been used to obtain the Class object for Meta:


Class c = Meta.class;

Of course, this approach only works when we know the class name of an object in advance, which might not always be the case. In general, we can obtain a class literal for classes, interfaces, primitive types, and arrays.

  • In the preceding example, myMeth( ) has no parameters. Thus, when getMethod( ) was called, only the name myMeth was passed. However, to obtain a method that has parameters, we must specify class objects representing the types of those parameters as arguments to getMethod( ). For example, here is a slightly different version of the preceding program:

// myMeth now has two arguments.
@MyAnno(str = "Two Parameters", val = 19)
public static void myMeth(String str, int i)
//...
// Here, the parameter types are specified.
Method m = c.getMethod("myMeth", String.class, int.class); //
The Class objects representing String and int are passed as additional arguments.

//...
public static void main(String args[]) {
myMeth("test", 10);
}

  • We can obtain all annotations that have RUNTIME retention that are associated with an item by calling getAnnotations( ) on that item. It has this general form:

Annotation[ ] getAnnotations( )

It returns an array of the annotations. getAnnotations( ) can be called on objects of type Class, Method, Constructor, and Field.

Here is another reflection example that shows how to obtain all annotations associated with a class and with a method. It declares two annotations. It then uses those annotations to annotate a class and a method.

// Show all annotations for a class and a method.
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
 

@Retention(RetentionPolicy.RUNTIME)
@interface What {
String description();
}

@What(description = "An annotation test class")
@MyAnno(str = "Meta2", val = 99)
class Meta2
{
 

@What(description = "An annotation test method")
@MyAnno(str = "Testing", val = 100)
public static void myMeth()
{
Meta2 ob = new Meta2();
try {
Annotation annos[] = ob.getClass().getAnnotations();
// Display all annotations for Meta2.
System.out.println("All annotations for Meta2:");
for(Annotation a : annos)
System.out.println(a);
System.out.println();
 

// Display all annotations for myMeth.
Method m = ob.getClass( ).getMethod("myMeth");
annos = m.getAnnotations();

System.out.println("All annotations for myMeth:");
for(Annotation a : annos)
System.out.println(a);
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}
The output is shown here:
All annotations for Meta2:
@What(description=An annotation test class)
@MyAnno(str=Meta2, val=99)
All annotations for myMeth:
@What(description=An annotation test method)
@MyAnno(str=Testing, val=100)

  • The methods getAnnotation( ) and getAnnotations( ) are defined by the AnnotatedElement interface, which is defined in java.lang.reflect.
    In addition, AnnotatedElement defines two other methods. The first is getDeclaredAnnotations( ), which has this general form:

Annotation[ ] getDeclaredAnnotations( )

It returns all non-inherited annotations present in the invoking object.

The second is isAnnotationPresent( ), which has this general form:

boolean isAnnotationPresent(Class annoType)

It returns true if the annotation specified by annoType is associated with the invoking object. It returns false otherwise.

  • We can give annotation members default values that will be used if no value is specified when the annotation is applied. A default value is specified by adding a default clause to a member’s declaration. It has this general form: 

    type member( ) default value;// value must be of a type compatible with type.

Here is @MyAnno rewritten to include default values:

// An annotation type declaration that includes defaults.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str() default "Testing";
int val() default 9000;

}

This declaration gives a default value of “Testing” to str and 9000 to val. This means that neither value needs to be specified when @MyAnno is used. However, either or both can be given values if desired. Therefore, following are the four ways that @MyAnno can be used:

@MyAnno() // both str and val default

@MyAnno(str = "some string") // val defaults

@MyAnno(val = 100) // str defaults

@MyAnno(str = "Testing", val = 100) // no defaults

  • A marker annotation is a special kind of annotation that contains no members. Its sole purpose is to mark a declaration. The best way to determine if a marker annotation is present is to use the method isAnnotationPresent( ), which is a defined by the AnnotatedElement interface. Here is an example that uses a marker annotation. Because a marker interface contains no members, simply determining whether it is present or absent is sufficient.

    import java.lang.annotation.*;
    import java.lang.reflect.*;

// A marker annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
// Annotate a method using a marker. Notice that no ( ) is needed.
@MyMarker

public static void myMeth() {
Marker ob = new Marker();
try {
Method m = ob.getClass().getMethod("myMeth");
// Determine if the annotation is present.
if(m.isAnnotationPresent(MyMarker.class))
System.out.println("MyMarker is present.");
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}

It is not wrong to supply an empty set of parentheses when linking marker with the method, but they are not needed.

  • A single-member annotation contains only one member. It works like a normal annotation except that it allows a shorthand form of specifying the value of the member. When only one member is present, we can simply specify the value for that member when the annotation is applied—we don’t need to specify the name of the member. However, in order to use this shorthand, the name of the member must be value. Here is an example that creates and uses a single-member annotation:

// A single-member annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MySingle {
int value(); // this variable name must be value
}
//...
// Annotate a method using a single-member annotation.
@MySingle(100) //Notice that value = need not be specified.
public static void myMeth() {
//...


We can use the single-value syntax when applying an annotation that has other members, but those other members must all have default values. For example, here the value xyz is added, with a default value of zero:

@interface SomeAnno {

int value();

int xyz() default 0;

}

In cases in which we want to use the default for xyz, we can apply @SomeAnno by simply specifying the value of value() by using the single-member syntax.

@SomeAnno(88)

In this case, xyz defaults to zero, and value gets the value 88. Of course, to specify a different value for xyz requires that both members be explicitly named, as shown here:

@SomeAnno(value = 88, xyz = 99)

  • Java defines many built-in annotations. Of these, four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited. Three—@Override, @Deprecated, and @SuppressWarnings—are included in java.lang.

  • @Retention - @Retention is designed to be used only as an annotation to another annotation. It specifies the retention policy.

  • @Documented - The @Documented annotation is a marker interface that tells a tool that an annotation is to be documented. It is designed to be used only as an annotation to an annotation declaration.

  • @Target - The @Target annotation specifies the types of declarations to which an annotation can be applied. It is designed to be used only as an annotation to another annotation.


@Target takes one argument, which must be a constant from the ElementType enumeration. This argument specifies the types of declarations to which the annotation can be applied. The constants are shown here along with the type of declaration to which they correspond.

  • ANNOTATION_TYPE - Another annotation

  • CONSTRUCTOR - Constructor

  • FIELD - Field

  • LOCAL_VARIABLE - Local variable

  • METHOD - Method

  • PACKAGE - Package

  • PARAMETER - Parameter

  • TYPE - Class, interface, or enumeration

We can specify one or more of these values in a @Target annotation. To specify multiple values, we must specify them within a braces-delimited list. For example, to specify that an annotation applies only to fields and local variables, we can use this @Target annotation:

@Target( { ElementType.FIELD, ElementType.LOCAL_VARIABLE } )

  • @Inherited - @Inherited is a marker annotation that can be used only on another annotation declaration. Furthermore, it affects only annotations that will be used on class declarations.


@Inherited causes the annotation for a superclass to be inherited by a subclass. Therefore, when a request for a specific annotation is made to the subclass, if that annotation is not present in the subclass, then its superclass is checked. If that annotation is present in the superclass, and if it is annotated with @Inherited, then that annotation will be returned.

  • @Override - @Override is a marker annotation that can be used only on methods.


A method annotated with @Override must override a method from a superclass. If it doesn’t, a compile-time error will result. It is used to ensure that a superclass method is actually overridden, and not simply overloaded.

  • @Deprecated - @Deprecated is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a newer form.

  • @SuppressWarnings - @SuppressWarnings specifies that one or more warnings that might be issued by the compiler are to be suppressed. The warnings to suppress are specified by name, in string form. This annotation can be applied to any type of declaration.

  • There are a number of restrictions that apply to annotation declarations:

  • First, no annotation can inherit another.

  • Second, all methods declared by an annotation must be without parameters. Furthermore, they must return one of the following:

  • A primitive type, such as int or double

  • An object of type String or Class

  • An enum type

  • Another annotation type

  • An array of one of the preceding types

  • Annotations cannot be generic. In other words, they cannot take type parameters.

  •   Finally, annotation methods cannot specify a throws clause.


Click for NEXT article.


Please feel free to correct me by commenting your suggestions and feedback.


Topic 33: Autoboxing in Java

  • Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object. 

  • Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed. There is no need to call a method such as intValue( ) or doubleValue( ).

  • With autoboxing it is no longer necessary to manually construct an object in order to wrap a primitive type. We need only assign that value to a type-wrapper reference. Java automatically constructs the object for us. For example, here is the modern way to construct an Integer object that has the value 100:

Integer iOb = 100; // autobox an int

Notice that no object is explicitly created through the use of new as discussed earlier in Type Wrappers. Java handles this for us, automatically.

  • To unbox an object, simply assign that object reference to a primitive-type variable. For example, to unbox iOb, you can use this line:

int i = iOb; // auto-unbox

  • Autoboxing automatically occurs whenever a primitive type must be converted into an object; auto-unboxing takes place whenever an object must be converted into a primitive type. Thus, autoboxing/unboxing might occur when an argument is passed to a method, or when a value is returned by a method. For example, consider this example:

// Take an Integer parameter and return an int value;
static int m(Integer v)
{
return v ; // auto-unbox to int
}


//Inside main() - Pass an int to m() and assign the return value to an Integer. Here, the argument 100 is autoboxed into an Integer. The return value is also autoboxed into an Integer.
Integer iOb = m(100);

  • In general, autoboxing and unboxing take place whenever a conversion into an object or from an object is required. This applies to expressions. Within an expression, a numeric object is automatically unboxed. The outcome of the expression is reboxed, if necessary. For ex:

Integer iOb
int i;

// The following automatically unboxes iOb, performs the increment, and then reboxes the result back into iOb.
++iOb;

// Here, iOb is unboxed, the expression is evaluated, and the result is reboxed and assigned to iOb2.
iOb = iOb + (iOb / 3);

// The same expression is evaluated, but the result is not reboxed.
i = iOb + (iOb / 3);

  • Auto-unboxing also allows you to mix different types of numeric objects in an expression. Once the values are unboxed, the standard type promotions and conversions are applied. For ex:

Integer iOb = 100;
Double dOb = 98.6;

dOb = dOb + iOb; // Results in 198.6

  • Because of auto-unboxing, we can use integer numeric objects to control a switch statement. For example, consider this fragment:

Integer iOb = 2;
switch(iOb)
{
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
default: System.out.println("error");
}

When the switch expression is evaluated, iOb is unboxed and its int value is obtained.

  • Java also supplies wrappers for boolean and char. These are Boolean and Character. Autoboxing/unboxing applies to these wrappers, too. For ex:

Boolean b = true;
// Below, b is auto-unboxed when used in a conditional expression, such as an if.
if(b) System.out.println("b is true");

// Autobox/unbox a char.
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char

Because of auto-unboxing, the boolean value contained within b is automatically unboxed when the conditional expression is evaluated. Thus, with the advent of autoboxing/unboxing, a Boolean object can be used to control an if statement. Because of auto-unboxing, a Boolean object can now also be used to control any of Java’s loop statements. When a Boolean is used as the conditional expression of a while, for, or do/while, it is automatically unboxed into its boolean equivalent. For example, this is now perfectly valid code:

Boolean b;
while(b) { // ...

  • Autoboxing/Unboxing can help us prevent errors. For ex:

Integer iOb = 1000; // autobox the value 1000
int i = iOb.byteValue(); // manually unbox as byte !!!
System.out.println(i); // does not display 1000 !

This displays not the expected value of 1000, but 24. The reason is that the value inside iOb is manually unboxed by calling byteValue( ), which causes the truncation of the value stored in iOb, which is 1,000. This results in the garbage value of 24 being assigned to i. Auto-unboxing prevents this type of error because the value in iOb will always auto- unbox into a value compatible with int.



Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.



 

Friday, January 29, 2016

Topic 32: Type Wrappers in Java


Despite the performance benefit offered by the primitive types, there are times when we will need an object representation. For example, we can’t pass a primitive type by reference to a method. Java provides type wrappers, which are classes that encapsulate a primitive type within an object.

  • The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean.

  • Character - Character is a wrapper around a char. The constructor for Character is


Character(char ch)


Here, ch specifies the character that will be wrapped by the Character object being created.


To obtain the char value contained in a Character object, call charValue( ), shown here:

char charValue( ) - It returns the encapsulated character.

  • Boolean - Boolean is a wrapper around boolean values. It defines these constructors:

Boolean(boolean boolValue)

Boolean(String boolString)

In the first version, boolValue must be either true or false. In the second version, if boolString contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.


To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:

boolean booleanValue( ) - It returns the boolean equivalent of the invoking object.

  • The Numeric Type Wrappers - Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number declares methods that return the value of an object in each of the different number formats. These methods are shown here:

byte byteValue( )

double doubleValue( )

float floatValue( )

int intValue( )

long longValue( )

short shortValue( )

doubleValue( ) returns the value of an object as a double, floatValue( ) returns the value as a float, and so on. These methods are implemented by each of the numeric type wrappers. All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value. For example, here are the constructors defined for Integer:

Integer(int num)

Integer(String str)

If str does not contain a valid numeric value, then a NumberFormatException is thrown.

  • All of the type wrappers override toString( ). This allows us to output the value by passing a type wrapper object to println( ), for example, without having to convert it into its primitive type.

The following demonstrates how to use a numeric type wrapper to encapsulate a value and then extract that value.

Integer iOb = new Integer(100);
int i = iOb.intValue();

System.out.println(i + " " + iOb); // displays 100 100


The process of encapsulating a value within an object is called boxing. For ex, the following line boxes the value 100 into an Integer:

Integer iOb = new Integer(100);

The process of extracting a value from a type wrapper is called unboxing. For ex, the program unboxes the value in iOb with this statement:

int i = iOb.intValue(); 

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

Topic 31: Enumerations in Java

  • In its simplest form, an enumeration is a list of named constants.

  • In Java, an enumeration defines a class type. That means, an enumeration can have constructors, methods, and instance variables.

  • An enumeration is created using the enum keyword. For example, here is a simple enumeration that lists various apple varieties:

enum Apple
{
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}

The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants. Each is implicitly declared as a public, static final member of Apple. Furthermore, their type is the type of the enumeration in which they are declared, which is Apple in this case. Thus, in the language of Java, these constants are called self-typed, in which “self” refers to the enclosing enumeration.

  • We can create a variable of enumeration type. We declare and use an enumeration variable in much the same way as we do one of the primitive types. For example, this declares ap as a variable of enumeration type Apple: 

    Apple ap;

Because ap is of type Apple, the only values that it can be assigned (or can contain) are those defined by the enumeration. For example, this assigns ap the value RedDel:

ap = Apple.RedDel; //RedDel is preceded by Apple.

  • Two enumeration constants can be compared for equality by using the = = relational operator. For example, this statement compares the value in ap with the GoldenDel constant:

if(ap == Apple.GoldenDel) // ...

  • An enumeration value can also be used to control a switch statement. Of course, all of the case statements must use constants from the same enum as that used by the switch expression. For example, this switch is perfectly valid:

switch(ap) {
case Jonathan:
// ...
case Winesap:
// ...

Notice that in the case statements, the names of the enumeration constants are used without being qualified by their enumeration type name. This is because the type of the enumeration in the switch expression has already implicitly specified the enum type of the case constants. There is no need to qualify the constants in the case statements with their enum type name. In fact, attempting to do so will cause a compilation error.

  • When an enumeration constant is displayed, such as in a println( ) statement, its name is output. For example, given this statement:

System.out.println(Apple.Winesap); //the name Winesap is displayed.

  • All enumerations automatically contain two predefined methods: values( ) and valueOf( ). Their general forms are shown here:

public static enum-type[ ] values( )

public static enum-type valueOf(String str)

The values( ) method returns an array that contains a list of the enumeration constants. The valueOf( ) method returns the enumeration constant whose value corresponds to the string passed in str. In both cases, enum-type is the type of the enumeration. For example:

// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);

// use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " + ap);

  • In Java, enumeration is a class type and each enumeration constant is an object of its enumeration type. When we define a constructor for an enum, the constructor is called when each enumeration constant is created. Also, each enumeration constant has its own copy of any instance variables defined by the enumeration. For example, consider the following version of Apple:

// Use an enum constructor, instance variable, and method.
enum Apple {
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

//Instance variable
private int price; // price of each apple

// Constructor
Apple(int p) { price = p; }

//Instance method
int getPrice() { return price; }
}

Apple ap;

// Display price of Winesap.
System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n");
// Display all apples and prices.
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");

When the variable ap is declared, the constructor for Apple is called once for each constant that is specified. Notice how the arguments to the constructor are specified, by putting them inside parentheses after each constant, as shown here:

Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

These values are passed to the p parameter of Apple( ), which then assigns this value to price.

Because each enumeration constant has its own copy of price, we can obtain the price of a specified type of apple by calling getPrice( ). For example:

Apple.Winesap.getPrice()

  • An enum can have two or more constructor overloaded forms, just as can any other class. For ex:

// Use an enum constructor.
enum Apple {
Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8);
private int price; // price of each apple


// Constructor
Apple(int p) { price = p; }

// Overloaded constructor
Apple() { price = -1; }

}

Notice that in this version, RedDel is not given an argument. This means that the default constructor is called, and RedDel’s price variable is given the value –1.

  • Enumeration can’t inherit another class and also cannot be a superclass. This means that an enum can’t be extended.This come with one exception, i.e. all enumerations automatically inherit one: java.lang.Enum. This class defines several methods that are available for use by all enumerations.

    We can obtain a value that indicates an enumeration constant’s position, called its ordinal value, in the list of constants by calling the ordinal( ) method, shown here:

final int ordinal( )

It returns the ordinal value of the invoking constant. Ordinal values begin at zero. Thus, in the Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel has an ordinal value of 1, RedDel has an ordinal value of 2, and so on.

We can compare the ordinal value of two constants of the same enumeration by using the compareTo() method. It has this general form:

final int compareTo(enum-type e)

Here, enum-type is the type of the enumeration, and e is the constant being compared to the invoking constant. Remember, both the invoking constant and e must be of the same enumeration. If the invoking constant has an ordinal value less than e’s, then compareTo( ) returns a negative value. If the two ordinal values are the same, then zero is returned. If the invoking constant has an ordinal value greater than e’s, then a positive value is returned.

We can compare for equality an enumeration constant with any other object by using equals( ), which overrides the equals( ) method defined by Object. Simply having ordinal values in common will not cause equals() to return true if the two constants are from different enumerations. Remember, we can compare two enumeration references for equality by using = =.

Apple ap, ap2, ap3;
// Obtain ordinal values using ordinal().
for(Apple a : Apple.values())
System.out.println(a + " " + a.ordinal());


ap =  Apple.RedDel;
ap2 = Apple.RedDel;

// Demonstrate compareTo() and equals()
if(ap.compareTo(ap2) < 0)
System.out.println(ap + " comes before " + ap2);

if(ap.equals(ap2))
System.out.println(ap + " equals " + ap2);
if(ap == ap2)
System.out.println(ap + " == " + ap2);


Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

Monday, January 25, 2016

Topic 30: MultiThreading in Java

  • Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. 

  • Threads are lightweight. They share the same address space and cooperatively share the same heavyweight process. 

    Interthread communication is inexpensive, and context switching from one thread to the next is low cost.

  • Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the wastage of CPU cycles.

  • Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

  • Thread priorities are integers that specify the relative priority of one thread to another. A thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules that determine when a context switch takes place are simple:

  • A thread can voluntarily relinquish control. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.

  • A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing— by a higher-priority thread. This is called preemptive multitasking.

For operating systems such as Windows, threads of equal priority are time-sliced automatically in round-robin fashion. For other types of operating systems, threads of equal priority must voluntarily yield control to their peers. If they don’t, the other threads will not run.

  • To synchronize two or more threads that share a resource, Java uses the monitor. We can think of a monitor as a very small box that can hold only one thread. Once a thread enters a monitor, all other threads must wait until that thread exits the monitor. In this way, a monitor can be used to protect a shared asset from being manipulated by more than one thread at a time. There is no class “Monitor”; instead, each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object.

  • After we divide our program into separate threads, we need to define how they will communicate with each other. Java provides a clean, low-cost way for two or more threads to talk to each other, via calls to predefined methods that all objects have. Java’s messaging system allows a thread to enter a synchronized method on an object, and then wait there until some other thread explicitly notifies it to come out.

  • Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable

    Thread encapsulates a thread of execution.  

    To create a new thread, our program will either extend Thread or implement the Runnable interface. 

  • When a Java program starts up, one thread begins running immediately. This is usually called the main thread. It is the one that is executed when program begins. The main thread is important for two reasons:

  • It is the thread from which other “child” threads will be spawned.

  • Often, it must be the last thread to finish execution because it performs various shutdown actions.

Main thread, like child threads, can be controlled through a Thread object. To do so, we must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here:

static Thread currentThread( )

This method returns a reference to the thread in which it is called. For example:

// Controlling the main Thread.
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);


// change the name of the thread
t.setName("My Thread"); //setName() changes the internal name of the thread
System.out.println("After name change: " + t);
try
{
for(int n = 5; n > 0; n--)
{
Thread.sleep(1000); //argument is delay period in milliseconds
}
}
//The sleep( ) method in Thread might throw an InterruptedException. This would happen if some other thread wanted to interrupt this sleeping one.
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}

Here is the output generated by this program:

Current thread: Thread[main,5,main]

After name change: Thread[My Thread,5,main]

Notice the output produced when t is used as an argument to println( ). This displays, in order: the name of the thread, its priority, and the name of its group. By default, the name of the main thread is main. Its priority is 5, which is the default value, and main is also the name of the group of threads to which this thread belongs. A thread group is a data structure that controls the state of a collection of threads as a whole. 

  • The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here:

static void sleep(long milliseconds) throws InterruptedException

The sleep( ) method has a second form, shown next, which allows to specify the period in terms of milliseconds and nanoseconds:

static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

This second form is useful only in environments that allow timing periods as short as nanoseconds.

  • We can set the name of a thread by using setName( ). We can obtain the name of a thread by calling getName( ) . These methods are members of the Thread class and are declared like this:
    final void setName(String threadName)
    final String getName( )

  • The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run( ), which is declared like this:

public void run( )

Inside run( ), we will define the code that constitutes the new thread. run( ) establishes the entry point for another, concurrent thread of execution within our program. This thread will end when run( ) returns.

After we create a class that implements Runnable, we will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName. After the new thread is created, it will not start running until we call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( ). The start( ) method is shown here:

void start( )

Here is an example that creates a new thread and starts it running:

// Create a second thread.
class NewThread implements Runnable
{
Thread t;

NewThread()
{
// Create a new, second thread
t = new Thread(this, "Demo Thread"); //constructor for Thread class

System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}


}


class ThreadDemo
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

After calling start( ), NewThread’s constructor returns to main( ). Both threads continue running, sharing the CPU, until their loops finish.


As mentioned earlier, in a multithreaded program, often the main thread must be the last thread to finish running. The preceding program ensures that the main thread finishes last, because the main thread sleeps for 1,000 milliseconds between iterations, but the child thread sleeps for only 500 milliseconds.

  • The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread. Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread
class NewThread extends Thread
{
NewThread()
{
// Create a new, second thread
super("Demo Thread");

System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Notice the call to super( ) inside NewThread. This invokes the following form of the Thread constructor:

public Thread(String threadName)

Here, threadName specifies the name of the thread.

  • Often we will want the main thread to finish last. Two ways exist to determine whether a thread has finished. 

    First, we can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown here:

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.


While isAlive( ) is occasionally useful, we will more commonly use join( ) to wait for a thread to finish, shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates.


Preceding example using Runnable interface and sleep() rewritten using join( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive( ) method.

NewThread ob1 = new NewThread();
System.out.println("Thread One is alive: " + ob1.t.isAlive());
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}

  • To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form:

final void setPriority(int level)

Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables within Thread.


We can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:

final int getPriority( )

The following example demonstrates two threads at different priorities. One thread is set two levels above the normal priority, as defined by Thread.NORM_ PRIORITY, and the other is set to two levels below it.

// Demonstrate thread priorities.
Thread t1 = new Thread(this);
Thread t2 = new Thread(this);

t1.setPriority(Thread.NORM_PRIORITY + 2);
t2.setPriority(Thread.NORM_PRIORITY - 2);

  • When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. Key to synchronization is the concept of the monitor (also called a semaphore).
    We can synchronize our code in either of two ways:

      Using Synchronized Methods

      Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method. To understand the need for synchronization, let’s begin with a simple example.

    // This program is not synchronized.
    class Callme
    {

    synchronized void call(String msg)
    {
    System.out.print("[" + msg);
    try
    {
    Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
    System.out.println("Interrupted");
    }
    System.out.println("]");
    }
    }
    class Caller implements Runnable
    {
    String msg;
    Callme target;
    Thread t;
    public Caller(Callme targ, String s)
    {
    target = targ;
    msg = s;
    t = new Thread(this);
    t.start();
    }
    public void run()
    {
    target.call(msg);
    }
    }
    class Synch
    {
    public static void main(String args[])
    {
    Callme target = new Callme();
    Caller ob1 = new Caller(target, "Hello");
    Caller ob2 = new Caller(target, "Synchronized");
    Caller ob3 = new Caller(target, "World");
    // wait for threads to end
    try
    {
    ob1.t.join();
    ob2.t.join();
    ob3.t.join();
    }
    catch(InterruptedException e)
    {
    System.out.println("Interrupted");
    }
    }
    }

    Here is the output produced by this program:

    [Hello] [Synchronized] [World]

    The synchronized Statement

    Suppose class was created by a third party, and we do not have access to the source code. Thus, we can’t add synchronized to the appropriate methods within the class. But we can simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement:

    synchronized(object) {

    // statements to be synchronized

    }

    Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor. Here is an alternative version of the preceding example, using a synchronized block within the run( ) method:

    // synchronize calls to call()
    public void run()
    {
    synchronized(target)


    { // synchronized block
    target.call(msg);
    }

    }

    • Interthread communication using final methods in Object wait( ), notify( ), notifyAll( ) methods. All classes have them.

      final void wait( ) throws InterruptedException

      final void notify( )

      final void notifyAll( )

      All three methods can be called only from within a synchronized context.

    wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

    notify( ) wakes up a thread that called wait( ) on the same object.

    notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access.

    Sun recommends that calls to wait( ) should take place within a loop that checks the condition on which the thread is waiting. The following example shows this technique.

    • The following sample program that implements a simple form of the producer/ consumer problem. It consists of four classes: Q representing the queue, Producer, the threaded object that is producing queue entries; Consumer, the threaded object that is consuming queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.

    class Q
    {
    int n;
    boolean emptyQ = false;

    synchronized int get()
    {
    while(!emptyQ)
    try
    {
    wait();
    }
    catch(InterruptedException e)
    {
    System.out.println("InterruptedException caught");
    }
    System.out.println("Got: " + n);
    emptyQ = false;
    notify();
    return n;
    }

    synchronized void put(int n)
    {
    while(emptyQ)
    try
    {
    wait();
    }
    catch(InterruptedException e)
    {
    System.out.println("InterruptedException caught");
    }
    this.n = n;
    emptyQ = true;
    System.out.println("Put: " + n);
    notify();
    }
    }

    class Producer implements Runnable
    {
    Q q;
    Producer(Q q)
    {
    this.q = q;
    new Thread(this, "Producer").start();
    }

    public void run()
    {
    int i = 0;
    while(true)
    {
    q.put(i++);
    }
    }
    }

    class Consumer implements Runnable
    {
    Q q;
    Consumer(Q q)
    {
    this.q = q;
    new Thread(this, "Consumer").start();
    }
    public void run()
    {
    while(true)
    {
    q.get();
    }
    }
    }

    class PC
    {
    public static void main(String args[])
    {
    Q q = new Q();
    new Producer(q);
    new Consumer(q);
    System.out.println("Press Control-C to stop.");
    }
    }

    • Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects. For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete.



    Click for NEXT article.



    Please feel free to correct me by commenting your suggestions and feedback.