core java for hadoop

69
Java.lang package tutorial Java.util package contains the classes that are fundamental to the design of the Java programming language. Java.lang Boolean Class The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. Class declaration Following is the declaration for java.lang.Boolean class: public final class Boolean extends Object implements Serializable, Comparable<Boolean> Java.lang.Byte Class

Upload: kavyashree-h-c

Post on 14-Apr-2017

290 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: core java for hadoop

Java.lang package tutorial

Java.util package contains the classes that are fundamental to the design of the Java programming language.

Java.lang Boolean Class

The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

Class declarationFollowing is the declaration for java.lang.Boolean class:

public final class Boolean

extends Object

implements Serializable, Comparable<Boolean>

Java.lang.Byte Class

The java.lang.Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.

Class declarationFollowing is the declaration for java.lang.Byte class:

public final class Byte

Page 2: core java for hadoop

extends Number

implements Comparable<Byte>

Java.lang.Character ClassThe java.lang.Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.

Class declarationFollowing is the declaration for java.lang.Character class:

public final class Character

extends Object

implements Serializable, Comparable<Character>

Java.lang.Character.Subset Class

The java.lang.Character.Subset class instances represent particular subsets of the Unicode character set. The only family of subsets defined in the Character class is UnicodeBlock.

Class declaration

Following is the declaration for java.lang.Character.Subset class:

public static class Character.Subset

Page 3: core java for hadoop

extends Object

Java.lang.Character.UnicodeBlock Class

The java.lang.Character.UnicodeBlock class is a family of character subsets representing the character blocks in the Unicode specification. Character blocks generally define characters used for a specific script or purpose.

Class declarationFollowing is the declaration for java.lang.Character.UnicodeBlock class:

public static final class Character.UnicodeBlock

extends Character.Subset

Java.lang.Class Class

The java.lang.Class class instance represent classes and interfaces in a running Java application.It has no public constructor.

Class declarationFollowing is the declaration for java.lang.Class class:

Page 4: core java for hadoop

public final class Class<T>

extends Object

implements Serializable, GenericDeclaration, Type, AnnotatedElement

Java.lang.ClassLoader ClassThe java.lang.ClassLoader class is an object that is responsible for loading classes. This class is an abstract class. It may be used by security managers to indicate security domains.

Class declarationFollowing is the declaration for java.lang.ClassLoader class:

public abstract class ClassLoader

extends Object

Java.lang.Compiler Class

The java.lang.Compiler class is provided to support Java-to-native-code compilers and related services. By design, it serves as a placeholder for a JIT compiler implementation.

Class declarationFollowing is the declaration for java.lang.Compiler class:

public final class Compiler

Page 5: core java for hadoop

extends Object

Java.lang.Double Class

The java.lang.Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

Class declarationFollowing is the declaration for java.lang.Double class:

public final class Double

extends Number

implements Comparable<Double>

Java.lang.Enum Class

The java.lang.Enum class is the common base class of all Java language enumeration types.

Class declarationFollowing is the declaration for java.lang.Enum class:

public abstract class Enum<E extends Enum<E>>

extends Object

implements Comparable<E>, Serializable

Page 6: core java for hadoop

Java.lang.Float Class

The java.lang.Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float.

Class declarationFollowing is the declaration for java.lang.Float class:

public final class Float

extends Number

implements Comparable<Float>

Java.lang.InheritableThreadLocal Class

The java.lang.InheritableThreadLocal class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values.

Class declarationFollowing is the declaration for java.lang.InheritableThreadLocal class:

public class InheritableThreadLocal<T>

extends ThreadLocal<T>

Page 7: core java for hadoop

Java.lang.Integer Class

The java.lang.Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

Class declarationFollowing is the declaration for java.lang.Integer class:

public final class Integer

extends Number

implements Comparable<Integer>

Java.lang.Long ClassThe java.lang.Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long.

Class declarationFollowing is the declaration for java.lang.Long class:

public final class Long

extends Number

implements Comparable<Long>

Page 8: core java for hadoop

Java.lang.Number Class

The java.lang.Number class is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.The Subclasses of Number must provide methods to convert the represented numeric value to byte, double, float, int, long, and short.

Class declarationFollowing is the declaration for java.lang.Number class:

public abstract class Number

extends Object

implements Serializable

Java.lang.Object Class

The java.lang.Object class is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

Class declarationFollowing is the declaration for java.lang.Object class:

public class Object

Page 9: core java for hadoop

Java.lang.Package Class

The java.lang.Package class contain version information about the implementation and specification of a Java package

Class declarationFollowing is the declaration for java.lang.Package class:

public class Package

extends Object

implements AnnotatedElement

Java.lang.Process Class

The java.lang.Process class provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

Class declarationFollowing is the declaration for java.lang.Process class:

public abstract class Process

extends Object

Page 10: core java for hadoop

Java.lang.ProcessBuilder Class

The java.lang.ProcessBuilder class is used to create operating system processes.This class is not synchronized.

Class declarationFollowing is the declaration for java.lang.ProcessBuilder class:

public final class ProcessBuilder

extends Object

Java.lang.Runtime Class

The java.lang.Runtime class allows the application to interface with the environment in which the application is running.

Class declarationFollowing is the declaration for java.lang.Runtime class:

public class Runtime

extends Object

Java.lang.RuntimePermission ClassThe java.lang.RuntimePermission class is for runtime permissions. A RuntimePermission contains a name (also

Page 11: core java for hadoop

referred to as a "target name") but no actions list; you either have the named permission or you don't.

Class declarationFollowing is the declaration for java.lang.RuntimePermission class:

public final class RuntimePermission

extends BasicPermission

Java.lang.String Class

The java.lang.String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.Strings are constant, their values cannot be changed after they are created

Class declarationFollowing is the declaration for java.lang.String class:

public final class String

extends Object

implements Serializable, Comparable<String>, CharSequence

Page 12: core java for hadoop

Java.lang.StringBuffer Class

The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are the important points about StringBuffer:

A string buffer is like a String, but can be modified. It contains some particular sequence of characters, but

the length and content of the sequence can be changed through certain method calls.

They are safe for use by multiple threads. Every string buffer has a capacity.

Class declarationFollowing is the declaration for java.lang.StringBuffer class:

public final class StringBuffer

extends Object

implements Serializable, CharSequence

oops:

Page 13: core java for hadoop

1)object oriented programming system(oops)

The features related to object oriented programming system are

1)class/object

2)Encapsulation

3)Abstraction

4)Inheritance

5)polymorpism

class/object:Entire oops metholodogy has been derived from a single root concept called object.An object is nothing that really exists in the worldand can be distiunshed from others.

string name;

int age;

char sex;

It is possible that some object s may have similar properties and objects .such objects belong to some category a class.

variables variables

name raju

Page 14: core java for hadoop

age 25

sex Male

methods methods

talking Talk()

walking walk()

eating eat()

A class is a modeal for creating objects and does not exit phyisically,An object is actually that exits phyisically,Both the class and objects contain variable and methods

Class person

//Properties of a person ---variable

string Name;

int age;

//Action done by a person --method

Void talk()

{

}

void eat()

Page 15: core java for hadoop

{

}

}

encapsulation:The encapsulation is achieved by combining the methods and attribute into a class.The class acts like a container.

Int id;

string name;

Encapsulation in java:

class person

{

//Variable _data

private string name;

private int age

//method

public void talk()

{

system.out.println("Hello,I am "+name);

system.out.println("my age is "+age);

}

Page 16: core java for hadoop

}

abastraction:There me be a lot af data a class contains and the user does not need the entire data.The user requires only some part of the available data. In these case ,we can hide the unnecessary data from the user and expose only the data is of interest to the user .This is called abstraction

Eg:Class bank

{

Privcate int accno;

private string name;

private float balance;

private float profit;

private float loan;

Public void display_to_cleark()

{

System.out.printl=n("aCCNO="+aCCNO);

System.out.printl=n("NAME="+name);

System.out.printl=n("balance="+balance);

}

}

Page 17: core java for hadoop

Inheritance:Inheritance is the property whicH Allows a child class to inherit some properties from its parent class.

class b extends a

{

}

eg:

class a

{

protected int a;

protected int b;

public void method ()

{

}

}

class b extends a

private int c;

public void method 2()

{

}

}

Page 18: core java for hadoop

polymorphism:

The word polymorphisim came from the greek word ply means many and morphos means meaning

The ability to define more than one function with the same name is called as ploymorphism

Class one

{

Void calculate (int x)]

{

system .out .println("square value ="+?(x*x));

}

}

class two extends one

{

void calculate (int x)

system.out.println("cute value="+(x*x*x));

}

}

Page 19: core java for hadoop

collections:

A collection Framework is a class library to handle goups of

objects collection is a framework implemented in

java.util.package

A collection object or a container object is an object which can

store a group of other objects.

java .util

collection class

collection objects

A group of objects stored in a single collection objects.

Sets: A set represents group of elements arranged just like an

array. The sets will grow dynamically when the elements are

stored into it. A set will not allow duplicate elements. If we try to

Page 20: core java for hadoop

pass the same element that is already in the set, then it is not

shared into the set.

List:

Lists are like sets ,they store a group of elements, But list

allows duplicate values to be stored.

Queues:

A queues represents arrangement of elements in FIFO(First in

first out) order. This means elements into the queue will be

removed first from the queue.

Maps:

Maps are stored elements in the form of key and value pairs .If

the key value is provided then it is corresponding value can be

obtained of course ,the key should have unique value.

Iterator interface:

Iterator is an interface that contains methods to retrieve the

elements one by one from a collection object. It has 3 methods

Page 21: core java for hadoop

Boolean has next():The method returns true if the iterator has

more elements.

Element next(): The method returns the next element in the

itetrator.

Void remove: This method removes from the collection the lost

elements returned by the iterator.

List Iterator Interface:

List iterator is an interface that contains methods retrieve the

elements from a collection object ,both in forward and reverse

diretions.

Enumeration interface: This interface is useful to retrieve one

by one elements like the Iterator It has 2 methods

Boolean has more elements():

Page 22: core java for hadoop

This method tests if the enumeration has any more elements or

not.

Elements next Elements():This returns the next element thats is

avilable in the Enumeration.

Java Exceptions :l

Exception are used in Java to handle errors or any other

exceptional event that occurs in the normal flow of program.

There are several way Exception can occur in Java.

Data provided is not in expected format(eg. int instead of

String).

DB can not connected.

Network connection Lost.

Object is null.

JVM running out of memory is a type of Error which can occur

at runtime.

Page 23: core java for hadoop

Overloading:

Overloaded method gives you an option to use the same

method name in a class but with different argument.

 Overloading Method Rules

There are some rules associated with overloaded method.

Overloaded methods

Must change the argument list

Can change the return type

Can change the access modifier(Broader)

Can declare new or broader checked exception

A method can be overloaded in Class or in SubClass.

 

Overloading Method Example

1

2

3

        //Overloaded method with two argument

public void add(int input1, int input2) {

System.out.println("In method with two argument");

Page 24: core java for hadoop

4

5

6

7

8

9

}

 

        //Overloaded method with one argument

public void add(int input1) {

System.out.println("In method with one argument");

}

Java Method Override:

Class inheriting the method from its super class has the option

to override it. Benefit of overriding is the ability to define

behaviour specific to particular class.

 

Method Overriding Example

1

2

3

4

5

public class ParentClass

{

public void show()

{

System.out.println("Show method of Super class");

Page 25: core java for hadoop

6

7

8

9

10

11

12

13

14

15

16

}

}

 

public class SubClass extends ParentClass

{

//below method is overriding the ParentClass version of show method

public void show()

{

System.out.println("Show method of Sub class");

}

}

Method Override Rules

Overriding method can not have more restrictive access

modifier than the method being overriden but it can be less.

The argument list must exactly match that of the overriden

method, if they don’t it is more likely that you are

overloading the method.

Return type must be the same as, or subtype of the return

type declared in overriden method in Super class.

Page 26: core java for hadoop

Overriding method can throw any unchecked

exception(Runtime)but it can throw checked exception

which is broader or new than those declared by the

overriden method but it can not throw fewer or narrow

checked exception.

Final  method can not be overriden.

Static  methods can not be overriden.

If a method cannot be inherited then it cannot be overriden.

HashMap

HashMap is HashTable based implementation of Map. This is

the reason why interviewer always ask for difference between

HashMap and HashTable. HashMap is mostly equals to

HashTable except below two differences.

1. HashMap is unsynchronized while HashTable is

synchronised. which means hash table can be shared

between multiple threads but hash map cannot be shared.

2. HashMap permits null while HashTable doesn’t.

Page 27: core java for hadoop

3. one more diference is that because of threads safety and

synchronization hash Table is mush slower than hash map

if used in single thread

Example of HashMap

1. How to iterate a Map

2. Different ways of iterating a Map

3. When HashCode and Equals will get called. (Pay close

attention to output of HashCode and equals method call)

12345678910111213141516

 import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set; public class HashMapExample {  public static void main(String[] args) {  Map<JBT, Integer> m1 = new HashMap<JBT, Integer>();  JBT t1 = new JBT(1, 2); JBT t2 = new JBT(1, 3); JBT t3 = new JBT(2, 1); 

Page 28: core java for hadoop

17181920212223242526272829303132333435363738394041424344454647484950515253

m1.put(t1, 1); m1.put(t2, 2); m1.put(t3, 3); System.out.println("Addition Done");  /* * Below you can find 3 different ways to iterate a Map. Uncomment * different section and see the different in Output. Pay attention to * when Hashcode and Equals is called */ /* Set s = m1.entrySet(); for (Iterator i = s.iterator(); i.hasNext();) { Map.Entry me = (Map.Entry) i.next(); System.out.println(me.getKey() + " : " + me.getValue()); }*//* for (Map.Entry<JBT, Integer> entry : m1.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); }*/ for (Object key : m1.keySet()) { System.out.println("Key : " + key.toString() + " Value : " + m1.get(key)); }  }} class JBT { JBT(int i, int j) { this.i = i; this.j = j;

Page 29: core java for hadoop

54555657585960616263646566676869707172737475767778

}  int i, j;  @Override public int hashCode() { System.out.println("Inside HashCode Method"); int k = i + j; return k; }  @Override public boolean equals(Object obj) {  System.out.println("Inside Equals Method"); if (i == ((JBT) obj).i && j == ((JBT) obj).j) return true; else return false; }  @Override public String toString() { return String.valueOf(i).concat(String.valueOf(j)); } } 

Java Hashtable class

o A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.

o It contains only unique elements.o It may have not have any null key or value.

Page 30: core java for hadoop

o It is synchronized.

Example of Hashtable:

1. import java.util.*;  2. class TestCollection16{  3.  public static void main(String args[]){  4.    5.   Hashtable<Integer,String> hm=new Hashtable<Integer,String

>();  6.   7.   hm.put(100,"Amit");  8.   hm.put(102,"Ravi");  9.   hm.put(101,"Vijay");  10.   hm.put(103,"Rahul");  11.   12.   for(Map.Entry m:hm.entrySet()){  13.    System.out.println(m.getKey()+" "+m.getValue());  14.   }  15.  }  16.

17. Output:103 Rahul18. 102 Ravi19. 101 Vijay20. 100 Amit

What is Serialization

Serialization is a process in which current state of Object will be

saved in stream of bytes. As byte stream create is platform

Page 31: core java for hadoop

neutral hence once objects created in one system can be

deserialized in other platform.

What is the use of Serialization

As written above serialization will translate the Object state to

Byte Streams. This B

yte stream can be used for different purpose.

Write to Disk

Store in Memory

Sent byte stream to other platform over network

Save byte stream in DB(As BLOB)

 

Serialization and Deserialization in Java

Now we know what is serialization. But in terms of Java how

this serialization will work and how to make a class serializable.

Java has already provided out of the box

way(java.io.Serializable Interface) to serialize an Object. If you

Page 32: core java for hadoop

want any class to be serialized then that class needs to

implement give interface.

Note*: Serializable Interface is a Marker Interface. Hence there

is no method in Serializable interface.

 

Code for Serialization of Java Class

Employee.java

123456789101112

 package com.jbt; import java.io.Serializable; public class Employee implements Serializable{   public String firstName;   public String lastName;   private static final long serialVersionUID = 5462223600l;} 

 

Page 33: core java for hadoop

SerializaitonClass.java

123456789101112131415161718192021222324252627

 package com.jbt; import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream; public class SerializaitonClass {  public static void main(String[] args) { Employee emp = new Employee(); emp.firstName = "Vivekanand"; emp.lastName = "Gautam";  try { FileOutputStream fileOut = new FileOutputStream("./employee.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(emp); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in ./employee.txt file"); } catch (IOException i) { i.printStackTrace(); } }} 

 

DeserializationClass.java

Page 34: core java for hadoop

12345678910111213141516171819202122232425262728

 package com.jbt; import java.io.*; public class DeserializationClass { public static void main(String[] args) { Employee emp = null; try { FileInputStream fileIn = new FileInputStream("./employee.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); emp = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserializing Employee..."); System.out.println("First Name of Employee: " + emp.firstName); System.out.println("Last Name of Employee: " + emp.lastName); }} 

First run “SerializaitonClass” and you will get “employee.txt”

file created.

Page 35: core java for hadoop

Second run “DeserializationClass” and java will deserialize

the class and value will be printed in console.

Output would be

12345

 Deserializing Employee...First Name of Employee: VivekanandLast Name of Employee: Gautam 

Java Interface 

Creating an Interface means defining a Contract. This Contract

states what a class can do without forcing how it should do.

 

Declaring an Interface

Interface can be defined with Interface keyword.

Page 36: core java for hadoop

Java Interface Example

1

2

3

4

5

6

7

public interface MyInterface

{

int i=0;

public void Height(int height);

public abstract void setHeight();

 

}

Rules for Declaring Interface

There are some rules that needs to be followed by Interface.

All Interface methods are implicitly public and abstract. Even

if you write these keyword it will not create problem as you

can see in second method declaration.

Interfaces can declare only Constant. Instance variables are

not allowed. It means all variables inside Interface must be

public, static, final. Variables inside interface are implicitly

public static final.

Page 37: core java for hadoop

Interface methods can not be static.

Interface methods can not be final, strictfp or native.

Interface can extend one or more other interface. Note:

Interface can only extend other interface.

Interface vs Abstract Class

Interface are like 100% Abstract Class. Interface can not

have non abstract methods while abstract class can have. A

Class Can implement more than one interface while Class can

extend only one class. As Abstract class comes in hierarchy of

Classes it can extend other classes too while Interface can only

extend Interfaces.

 

Use Interface in Class

How can we take the advantage of Interface after creating it in

Java. To take the advantage we need to implement or class

Page 38: core java for hadoop

with given Interface. Implement    keyword can be used for this

purpose.

Examples of Class Implementing Interface

Example 1:

1

2

3

4

5

6

7

public class InterfaceExampleOne implements interfaceOne {

 

}

 

interface interfaceOne {

 

}

 

Example 2:

1

2

3

4

5

/*

* As implmeneted Interface have any abstract method so this class

* need to implement any method.

*/

Page 39: core java for hadoop

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

class InterfaceExampleTwo implements interfaceTwo {

 

@Override

public void methhod() {

System.out.println(var);

}

 

}

 

/*

* Below interface has an abstract method so implemented class needs to

* implement this method unless and untill it is abstract itself

*/

interface interfaceTwo {

public final int var = 9;

 

public abstract void methhod();

}

Example 3:

1

2

/*

* As below class is not abstract class and it is extending

Page 40: core java for hadoop

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

abstract class which

* has not yet implemented the method from interface so this class is FORCED to

* implement method from Interface in hierarachy(interfaceTwo).

*/

class InterfaceExampleTwo extends InterfaceExampleThree {

 

@Override

public void methhod() {

System.out.println(var);

}

 

}

 

/*

* Below interface has an abstract method so implemented class needs to

* implement this method unless and untill it is abstract itself

*/

interface interfaceTwo {

public final int var = 9;

Page 41: core java for hadoop

25

26

27

28

29

30

31

32

33

34

 

public abstract void methhod();

}

 

/*

* Even if Interface has abstract method ABSTRACT CLASS is not forced to

* implement it. Abstract class may/may not navigate this responsibility of

* implementing abstract method to class which is not abstract.

*/

abstract class InterfaceExampleThree implements interfaceTwo {

 

// Method from Interface is not implemented here

 

}

Java Thread   :

Thread term can be used in two ways

An instance of class java.lang.Thread

Page 42: core java for hadoop

A Thread of Execution

An Instance of Thread is an object like any other object in Java,

it contains variables and methods which lives and dies on the

heap. But a Thread of Execution is an individual process  which

has its ownstack call. Even if you don’t create any thread in

your program, thread will be running there and main() method

will start that.

Note: In case of thread most of thing is unpredictable.

Type of Thread

Thread can be of two types.

User Thread

Daemon Thread

Page 43: core java for hadoop

Difference between these two type of thread is that JVM exit an

application only when all User Thread are complete. JVM

doesn’t care about the status of Daemon Thread.

Thread Definition

A thread can be defined in two ways

Extend the java.lang.Thread class.

Implement the Runnable interface.

Extending Java Thread class:

Class need to extend the Thread class & Override the

run()method.

1

2

3

4

5

6

7

class MyThread extends Thread

{

public void run()

{

System.out.println("Important job running in MyThread");

}

}

Page 44: core java for hadoop

But the problem with this approach is that class can not extend

any more class.

Note : run method can be overloaded in class. but only run()

method(without argument) will be consider by JVM. Any other

overridden method will needs to be called explicitly.

Implements runnnable interface

Class needs to implement runnable interface and override the

run() method. Creating Thread in this way gives you flexibility

to extend any class you like.

1

2

3

4

5

6

7

class MyRunnable implements Runnable {

 

public void run() {

 

System.out.println("Important job running in MyRunnable");

 

} }

Page 45: core java for hadoop

Instantiating Thread :

Every thread of execution begins as an instance of class

Thread. In any case Thread objects needs to be created before

creating Thread of Execution.

Creating Thread object is different for both the cases. In case of

Extending Thread class you can directly initiate class with new

keyword as it has extended Thread class itself.

1 MyThread t = new MyThread()

In case of implimenting Runnable interface. First created

runnable class needs to be instatiated.

1 MyRunnable r = new MyRunnable();

Now pass this runnable object to Thread.

1 Thread t = new Thread(r);

If you create a thread using the no-arg constructor, the thread

will call its own run(). This happened in first case(Extending

Thread class) But in case of Runnable Thread class needs to

know that run method from class implementing runnnable

interface needs to be invoked instead of run() from Thread

Page 46: core java for hadoop

class. So we need to pass the class as argument to Thread.

Single runnable instance can be passed to multiple Thread

object.

1

2

3

4

5

6

7

8

9

10

11

12

public class TestThreads {

 

public static void main (String [] args) {

 

MyRunnable r = new MyRunnable();

 

Thread foo = new Thread(r);

 

Thread bar = new Thread(r);

 

Thread bat = new Thread(r);

}}

Giving the same target to multiple threads means that several

threads of execution will be running the very same job (and that

the same job will be done multiple times).

Page 47: core java for hadoop

Note : The Thread class itself implements Runnable. (After all,

it has a run() method that we were overriding.) This means that

you could pass a Thread to another Thread’s constructor.

Overloaded constructor in Thread class:

1

2

3

4

Thread()

Thread(Runnable target)

Thread(Runnable target, String name)

Thread(String name)

Till now we have created Thread object and it knows what to do

in form of run() method. But till now it is still an object. It does

not have its own call stack. In other words Thread of execution

has not been started. A Thread object will have its own stack

only when start() method will be called on Thread.

Till now Thread has 2 states.

New state (Thread object created but Start method not

invoked)

runnable(alive) state (start method is invoked )

Page 48: core java for hadoop

Note : Calling run() method from java code directly mean that

you are invoking a method and stack will not be created.

When a Thread is in runnable state means Thread is created

but it’s run method is not yet executed and thread is waiting for

his turn. Once Thread got selected thread’s run method will

execute and that state will called running state.

Thread Scheduler :

The thread scheduler is the part of the JVM that decides which

thread should run at any given moment, and also takes threads

out of the run state. Any thread in the runnable state can be

chosen by the scheduler to be the one and only running thread.

If a thread is not in a runnable state, then it cannot be chosen

to be the currently running thread. Some method that can

influence scheduler to some extent(Note*: We can’t control the

behavior of Thread scheduler)

These methods are from Thread class

1

2

* public static void sleep(long millis) throws InterruptedException

Page 49: core java for hadoop

3

4

* public static void yield()

* public final void join() throws InterruptedException

* public final void setPriority(int newPriority)

Methods from Object class.

1

2

3

* public final void wait() throws InterruptedException

* public final void notify()

* public final void notifyAll()

Till now we come across 3 state of Thread

 New

 Runnable

 Running

There are some more state of thread in which Thread will not

be eligible to run.

Waiting/blocked/sleeping

Dead

A thread is in Dead state when its run method completed its

execution.

Page 50: core java for hadoop

Sleeping

The sleep() method is a static method of class Thread. (where

it still has to beg to be the currently running thread). as it is

static method only currently running Thread will sleep. Syntax

would be : Thread.sleep()

yield: yield method is related with the priority of Thread. It is

also static method so it works only on currently running thread.

Scheduler make it sure that If a thread enters the runnable

state, and it has a higher priority than any of the threads in the

pool and a higher priority than the currently running thread, the

lower-priority running thread usually will be bumped back to

runnable and the highest-priority thread will be chosen to run.

at any given time the currently running thread usually will not

have a priority that is lower than any of the threads in the pool.

yield() is supposed to do is make the currently running thread

head back to runnable to allow other threads of the same

priority to get their turn.

Page 51: core java for hadoop

Join()

Join is a non static method. It lets one thread “join onto the end”

of another thread. If you join Thread B to Thread A Thread B

will not start untill Thread A complets.

Syntax :

1

2

3

Thread t = new Thread();

t.start();

t.join();

takes the currently running thread and joins it to the end of the

thread referenced by t

There are several other way in which Thread can leave running

state and can return to Runnable state. run methods completes

a call to wait()

Synchronize: It works with Lock. Lock is of two type.

Static lock

Non static lock

Page 52: core java for hadoop

Note: There is only one lock per object. Once a thread got the

lock of an object no other thread can enter the synchronise

block/method of given object.

Only methods/block can be synchronised not variable or class.

A class can have both synchronised / non synchronised

method.

Thread can access non synchronised block even if one Thread

got the lock of give object.

If a thread goes to sleep, it holds any locks it has. A thread can

have Lock of different object at the same time.

Syntax :

1

2

3

4

5

6

7

8

class SyncTest {

 

public void doStuff() {

 

System.out.println("not synchronized");

 

synchronized(this) {

 

Page 53: core java for hadoop

9

10

11

System.out.println("synchronized");

 

}}}

Synchronised Static method :

There is only one copy of the static data, so you only need one

lock per class to synchronize static methods—a lock for the

whole class. There is such a lock; every class loaded in Java

has a corresponding instance of java.lang.Class representing

that class. It’s that java.lang.Class instance whose lock is used

to protect the static methods of the class.

Syntax:

1

2

3

4

5

public static synchronized int getCount() {

 

return count;

 

}

MyClass.class thing is called a class literal. It tells the compiler

(who tells the JVM): go and find me the instance of Class that

represents the class called MyClass.

Page 54: core java for hadoop

Note : Threads calling non-static synchronized methods in the

same class will only block each other if they’re invoked using

the same instance. As there is only one lock per instance.

Threads calling static synchronized methods in the same class

will always block each other— As there is only one lock per

class.

A static synchronized method and a non-static synchronized

method will not block each other. As they need lock for different

thing(Object & class)

Note : join(), sleep(), yield() these methods keep locks. while

wait release Lock.

What are mutable objects and immutable objects?An Immutable object is a kind of object whose state cannot be modified after it is created. This is as opposed to a mutable object, which can be modified after it is created.

In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer,Long, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String.

Page 55: core java for hadoop

class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); str.toLower(); System.out.println(str); }}

The output result is

HELLOHELLOFrom the above example, the toLower() method does not impact on the original content in str. What happens is that a new String object "hello" is constructed. The toLower() method returns the new constructed String object's reference. Let's modify the above code:class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); String str1 = str.toLower(); System.out.println(str1); }}

The output result is

HELLOhelloThe str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor.

"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, you should still limit its mutability as much as possible."

Page 56: core java for hadoop