Monday, 13 July 2015

Java Synchronization

Because multi-threading introduces an asynchronous behaviour to your programs, there must be a way for you to enforce synchronization when you need it.

For example, if you want two threads to communicate and share a complicated data structure, such as a linked list, you need some way to ensure that they do not conflict with each other.

That is, you must prevent one thread from writing data while another thread is in the middle of reading it. Java uses monitor for inter-thread synchronization.

You 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.

Most multi-threaded systems expose monitors as objects that your program must explicitly acquired and lock. Java provides a cleaner solution.

There is no class "monitor", instead, each object has its own implicit monitor that is automatically entered when one of the object's synchronized method is called.

Once a thread is inside a synchronized method no other thread can call any other synchronized method on the same object. This enables you to write very clear and concise multi-threaded code, because synchronization support is built into the language.

Java Thread Priorities

Java assigns to each thread a priority that determines how that thread should be treated with respect to the others.

Thread priorities are integers that specify the relative priority of one thread to another. As an absolute value, a priority is meaningless; a higher-priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next. This is called a ontext switch.

The rules that determine when a context switch takes place are simple:

  • A thread can voluntarily (on its own) relinquish control. This is done by explicitly yielding, sleeping or blocking on pending I/O. In this scenario, all other threads are examined, and normally the highest-priority thread that is ready to run is given the CPU.

  • A thread can be pre-empted by a higher-priority thread. In this case, a lower priority thread that does not yield the processor is simply pre-empted no matter what it is doing, by a higher priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. Some OS support non-preemptive priority based scheduling. In such case a high priority thread gets chance only when low priority thread completes.
  • In cases where two threads with the same priority are competing for CPU cycles, the situation is a bit complicated. For OS such as windows 98, threads of equal priority are normally time-sliced automatically in the round-robin fashion. For other types of OS's, thread of equal priority must voluntarily (on their own) yield (give) control to their peers. If they do not, the other threads will not run.

Note: Problems can arise from the differences in the way that O.S.’s context-switch threads of equal priority.

Java Thread Life Cycle (Thread States)

Thread exists 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.

1. Newborn State

When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:

1. Schedule it for running using the start() method.

2. Kill it using stop() method

If scheduled, it moves to runnable state. If we attempt to use any other method at this stage, an exception will be thrown.

2. Runnable State

The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads are of equal priority, then normally they are given time slots for execution in round robin fashion. The thread that relinquishes control joins the queue at the end and again waits for its run. However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, it can do so by invoking the yield() method.

3. Running State

Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.

A running thread may relinquish its control in one of the following situations:

  • Its time-slice is over
  • It is pre-empted by a higher priority thread
  • It yields i.e. voluntarily gives up control.
  • It has completed its execution
  • It is stopped by some other thread.
  • It has been suspended using suspend() method; a suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.
  • It has been made to sleep. We can put a thread to sleep for a specified time period using the static method sleep(time) of Thread class where time is in milli-seconds. This means that the thread is out of the queue during the time period. The thread re-enters the runnable state as soon as this time period is elapsed.
  • It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method.
  • It is performing some I/O operation.

4. Blocked State

A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

5. Dead State

Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It has a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death. A thread can be killed as soon as it is born, or while it is running, or even when it is in “not runnable” (blocked condition).

Wednesday, 8 July 2015

Java Multi-Threaded Programming

1. Introduction

A thread is a single flow of control within a program. Thread is very much similar to a process. In fact, the thread is also called a lightweight process.

1.1 Thread v/s Process

Normally different processes occupy different memory space. When the CPU shifts from one process to another process, the state of the currently running process is saved and the state of another process is restored. No useful work is being done during state switch. This is referred to as context switch. The context switch time should be as less as possible to maximize the CPU utilization.

Threads are also like independent processes but they share the same memory and state. The separate threads also have separate state but the state is very small as compared to process state.

The state may contain just program counter and stack pointer. So switching from one thread to another thread takes very little time. Thus the context switch time for threads is very small as compared to the process. Hence CPU utilization is high in case of multiple threads as compared to the utilization in case of multiple processes. Threads are also referred to as light-weight process.

1.2 Multi-Threaded program

A multi-threaded 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, multi-threading is a specialized form of multi-tasking.

For example, a program may have three threads:

  • One handling the printing
  • One handling the editing
  • One downloading a file from the Internet.

All these threads might be running concurrently thus maximizing the CPU utilization.

1.3 Process-based Multi-tasking


Most of the operating systems allow you to run two or more programs at the same time. It is referred to as process-bases multi-tasking. For example, you can run a Java program and at the same time you may be editing a word document. The process-based multi-tasking ensures that there will be some program to be executed most of the time so it increases the CPU utilization.  

In process-based multi-tasking, a program is the smallest unit of code that can be dispatched by the scheduler.

1.4 Thread-based multi-tasking

Thread is the smallest unit of execution in a thread-based multi-tasking environment. A process can be divided into a number of threads executing concurrently. This allows us to handle more than one task concurrently in a single program. For example, you can edit a word document and at the same time print a portion of it or another document.

Thread-based multi-tasking improves CPU utilization just like process-based multi-tasking. But at the same time it effectively speeds up the execution of a single program by executing its different parts concurrently in separate threads.

Thus process based multi-tasking deals with the “big picture”, and thread-based multi-tasking handles the details.

1.5 The Java Thread Model

The Java run-time system depends on threads for many things, and all the class libraries are designed with multi-threading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles.

Single threaded systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next. In a single threaded environment, when a thread blocks (that is, suspends execution) because it is waiting for some resource, the entire program stops running.

The benefit of Java's multi-threading is that the main loop/polling mechanism is eliminated.

When a thread blocks in Java program, only the single thread that is blocked pauses, all other threads continue to run.

Tuesday, 23 June 2015

Java Wrapper Classes

1. Introduction

The primitive data types in Java are not objects as already discussed. If we want to use these data types as objects, then we will have to use wrapper classes for each of these primitive data types provided in java.lang package.

There are many built-in classes, which cannot handle primitive data types as they deal only with objects.  One such class is Vector, which is used to store a collection of objects. We cannot use

the Vector class to directly store the collection of elements of a primitive data type. But we can do so by storing the objects of wrapper classes, which correspond to the primitive data types.

Java has a wrapper class corresponding to each of the primitive data types as shown in the following table:


2. Number class

The abstract class Number defines a super-class that is implemented by the classes that wrap the numeric types byte, short, int, long, float, and double. The number class has abstract methods that return the value of the object in each of the different number formats. These methods are:


The values returned by byteValue(), shortValue(), intValue(), longValue(), floatValue() and doubleValue() methods may involve rounding or truncation.

Example: The following example demonstrates how rounding and truncation take place when invoking methods of class Number.

class Wrapper

{ public static void main(String args[])

{ Integer iObj = new Integer(257);

System.out.println(iObj.byteValue());//truncation

Long lObj = new Long(123456789123456789L);

System.out.println(lObj);

System.out.println(lObj.doubleValue());

Float fObj=new Float(3.99f);

System.out.println(fObj.intValue());//truncation

}

}

Output:

1

123456789123456789

1.23456789123456784E17

3

3. Converting Primitive Numbers to Objects using Constructors of Wrapper

Classes and Converting Numeric Objects Back to Primitive Numbers

Example: The following example demonstrates how primitives can be wrapped in objects and how they can be converted back to primitives.

class Convert

{ public static void main(String args[])

{ System.out.println("Converting primitive numbers to objects "+

"using constructor");

byte b=105;

Byte bObj=new Byte(b);

System.out.println(bObj);

short s=2015;

Short sObj=new Short(s);

System.out.println(sObj);

int i=32717;

Integer iObj=new Integer(i);

System.out.println(iObj);

long l=234543335565675L;

Long lObj=new Long(l);

System.out.println(lObj);

float f=3.1415f;

Float fObj=new Float(f);

System.out.println(fObj);

double d=3.1415;

Double dObj=new Double(d);

System.out.println(dObj);

System.out.println("Converting numeric objects to primitive numbers");

byte b1=bObj.byteValue();

short s1=sObj.shortValue();

int i1=iObj.intValue();

long l1=lObj.longValue();

float f1=fObj.floatValue();

double d1=dObj.doubleValue();

System.out.println(b1);

System.out.println(s1);

System.out.println(i1);

System.out.println(l1);

System.out.println(f1);

System.out.println(d1);

}

}

Output:

Converting primitive numbers to objects using constructor

105

2015

32717

234543335565675

3.1415

3.1415

Converting object numbers to primitive numbers

105

2015

32717

234543335565675

3.1415

3.1415

4. Converting Primitive Numbers to Strings using toString() static method of the corresponding Wrapper Class

Example:

class ConvertPrimitiveToString

{

public static void main(String args[])

{

System.out.println("Converting primitive numbers to String "+

"using toString() static method of corresponding wrapper class:");

byte b=105;

String str=Byte.toString(b);

System.out.println(str);

short s=303;

str=Short.toString(s);

System.out.println(str);

int i=100;

str=Integer.toString(i);

System.out.println(str);

long l=4544444444444l;

str=Long.toString(l);

System.out.println(str);

float f=3.444f;

str=Float.toString(f);

System.out.println(str);

double d=3.44444;

str=Double.toString(d);

System.out.println(str);

}

}

Output:

Converting primitive numbers to String using toString() static method of corresponding wrapper

class:

105

303

100

4544444444444

3.444

3.44444

5. Converting Numeric Objects to Strings using toString() method of the corresponding Wrapper Class

Example:

class ObjectToStringDemo

{

public static void main(String args[])

{

System.out.println("Converting object numbers to Strings using "+

"toString() method of corresponding wrapper class:");

byte b=103;

Byte bObj=new Byte(b);

String str=bObj.toString();

System.out.println(str);

short s=203;

Short sObj=new Short(s);

str=sObj.toString();

System.out.println(str);

Integer iObj=new Integer(32000);

str=iObj.toString();

System.out.println(str);

str=new Long(4544444444444l).toString();

System.out.println(str);

str=new Float(3.1444f).toString();

System.out.println(str);

str=new Double(4.1444).toString();

System.out.println(str);

}

}

Output:

Converting object numbers to Strings using toString() method of the corresponding wrapper class:

103

203

32000

4544444444444

3.1444

4.1444

6. Converting String Objects (Numeric Strings) to Numeric Objects using the static valueOf() method of the corresponding Wrapper Class

Example:

class StringToNumericObjectDemo

{ public static void main(String args[])

{ String str="30";

//String str=new String("30");

String str2="30.333";

Byte bObj=Byte.valueOf(str);

//Byte bObj1=new Byte(str2); //NumberFormatException

Short sObj=Short.valueOf(str);

Integer iObj=Integer.valueOf(str);

Long lObj=Long.valueOf("344324232432");

Float fObj=Float.valueOf("3.333");

Double dObj=Double.valueOf(str2);

System.out.println(bObj);

System.out.println(sObj);

System.out.println(iObj);

System.out.println(lObj);

System.out.println(fObj);

System.out.println(dObj);

}

}

Output:

30

30

30

344324232432

3.333

30.333

Note: All of the valueOf( ) methods throw “NumberFormatException” if the string does not contain a parsable number.

7. Converting String Objects (Numeric Strings) to Numeric Objects using Constructor of the corresponding Wrapper Class

Example:

class StringToNumericObjectDemo1

{ public static void main(String args[])

{ String str=new String("30");

//String str="30";

String str2=new String("30.333");

Byte bObj=new Byte(str);

//Byte bObj1=new Byte(str2); //NumberFormatException

Short sObj=new Short(str);

Integer iObj=new Integer(str);

Long lObj=new Long(str);

Float fObj=new Float(str2);

Double dObj=new Double(str2);

System.out.println(bObj);

System.out.println(sObj);

System.out.println(iObj);

System.out.println(lObj);

System.out.println(fObj);

System.out.println(dObj);

}

}

Output:

30

30

30

30

30.333

30.333

Note: The Above constructors throw “NumberFormatException” if the string does not contain a parsable number.

8. Converting String Objects (Numeric Strings) to Primitive Numbers using parsing method of the corresponding Wrapper Class

Example:

class StringToPrimitiveDemo

{ public static void main(String args[])

{ String str=new String("30");

//String str="30";

String str2=new String("30.333");

byte b=Byte.parseByte(str);

//byte b1=Byte.parseByte(str2); //NumberFormatException

short s=Short.parseShort(str);

int i=Integer.parseInt(str);

long l=Long.parseLong(str);

float f=Float.parseFloat(str2);

double d=Double.parseDouble(str2);

System.out.println(b);

System.out.println(s);

System.out.println(i);

System.out.println(l);

System.out.println(f);

System.out.println(d);

}

}

Output:

30

30

30

30

30.333

30.333

Note: parseXXX( ) methods throw “NumberFormatException” if the string does not contain a parsable number.

9. Constants defined in classes Double and Float

MAX_VALUE

MIN_VALUE

NaN

NEGATIVE_INFINITY

POSITIVE_INFINITY

TYPE    (The Class instance representing the primitive type double/float)

SIZE     (The number of bits used to represent a double value). Since J2SDK 1.5.

10. Other Methods in Float Class



11. Constants defined in classes Byte, Short, Integer and Long

Methods in the Double class are almost the same as methods of the Float Class; with the use of double and Double words instead of float and Float words in the previous table.

12. Constants defined in classes Byte, Short, Integer and Long

MIN_VALUE

MAX_VALUE

TYPE   (The Class instance representing the primitive type byte/short/int/long)

SIZE The number of bits used to represent a byte/short/int/long value in two's complement binary form. Since J2SDK 1.5.

13. Other Methods in Byte Class



 14. Other Methods in Short Class

Methods in the Short class are the same as methods of the Byte class, with the use of short and Short words instead of byte and Byte words in the above table.

15. Other Methods in Integer Class





16. Other Methods in Integer Class

Methods in the Long class are almost the same as methods of the Integer Class.

17. Character Class

The Character class wraps a value of the primitive type char in an object.

Constructor

Character(char value)

Constructs a newly allocated Character object that represents the specified char value.

Example: Character chObj = new Character(‘A’);

Methods

Some of the methods of Character class are described in the following table:



 Example:

class CharacterDemo1

{ public static void main(String args[])

{ char ch[]={'a', 'b','5','?','A',' '};

for(int i=0; i<ch.length;i++)

{ if(Character.isLowerCase(ch[i]))

if(Character.isDigit(ch[i]))

if(Character.isLetter(ch[i]))

if(Character.isUpperCase(ch[i]))

if(Character.isWhitespace(ch[i]))

System.out.println(ch[i]+" is lowercase");

System.out.println(ch[i]+" is a digit");

System.out.println(ch[i]+" is a letter");

System.out.println(ch[i]+" is in uppercase");

System.out.println(ch[i]+" is a whitespace");

}

System.out.println(Character.isLetter(65)); //for 'A'

System.out.println(Character.isLetter(64)); //for '@'

}

}

Output:

a is lowercase

a is a letter

b is lowercase

b is a letter

5 is a digit

A is a letter

A is in uppercase

  is a whitespace

true

false

18. Boolean Class

The Boolean class wraps a value of the primitive type boolean in an object.

18.1 Constructors


18.2 Methods of Boolean Class



Example: The Stack class in the following example represents a generalized stack as it is using an array of objects to store the elements. The StackDemo class creates three instances and uses them to store primitive data types using wrapper classes.

class Stack

{

int top = -1;

int size;

Object a[];

Stack(int size)

{

this.size = size;

a = new Object[size];

}

void push(Object x)

{

if(top == size-1)

{

System.out.println("Stack Full");

return;

}

top = top + 1;

a[top] = x;

}

Object pop()

{

if(top ==  -1)

{

return null;

}

Object x = a[top];

top = top - 1;

return x;

}

}

class StackDemo

{

public static void main(String args[])

{

Stack s1 = new Stack(10);

Stack s2 = new Stack(10);

Stack s3 = new Stack(10);

s3.push(new Integer(10));

s3.push(new Long(20L));

s3.push(new Float(13.5));

s3.push(new Double(14.5));

for(int i = 0; i < 10; i++)

{ s1.push(new Integer(i));

}

for(int i = 10; i < 20; i++)

{ s2.push(new Float(i+0.5));

}

Object x; int sum = 0;

for(int i = 0; i < 10; i++)

{ x = s1.pop(); System.out.print(x + " ");

int a = ((Integer)x).intValue();

sum = sum+a;

}

float fsum = 0;

System.out.println("\n sum: "+sum);

for(int i = 0; i < 10; i++)

{

x = s2.pop();

System.out.print(x +" ");

float f = ((Float)x).floatValue();

fsum = fsum+f;

}

System.out.println("\n sum: " + fsum);

double dsum = 0;

while((x = s3.pop()) != null)

{ System.out.print(x +" ");

if(x instanceof Integer)

if(x instanceof Long)

if(x instanceof Float)

if(x instanceof Double)

}

System.out.println("\n sum: " + dsum);

dsum= dsum + ((Integer)x).intValue();

dsum= dsum + ((Long)x).longValue();

dsum= dsum + ((Float)x).floatValue();

dsum= dsum + ((Double)x).doubleValue();

}

}

Output:

9 8 7 6 5 4 3 2 1 0

 sum: 45

19.5 18.5 17.5 16.5 15.5 14.5 13.5 12.5 11.5 10.5

 sum: 150.0

14.5 13.5 20 10

 sum: 58.0