0% found this document useful (0 votes)
9 views23 pages

JAVA Unit4

Uploaded by

imvrsk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views23 pages

JAVA Unit4

Uploaded by

imvrsk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

JAVA –Unit4 PESIAMS,Shimoga

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class


provides constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.

Java Thread Methods

S.N. Modifier and Method Description


Type

1) void start() It is used to start the execution of


the thread.

2) void run() It is used to do an action for a


thread.

3) static void sleep() It sleeps a thread for the specified

Darshan P R, Asst. Professor Page 1


JAVA –Unit4 PESIAMS,Shimoga

amount of time.

4) static Thread currentThread() It returns a reference to the


currently executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the


thread.

A thread in Java at any point of time exists in any one of the following states. A
thread lies only in one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Terminated
The diagram shown below represents various states of a thread at any instant in
time.

Darshan P R, Asst. Professor Page 2


JAVA –Unit4 PESIAMS,Shimoga

Life Cycle of a thread


1. New Thread: When a new thread is created, it is in the new state. The thread
has not yet started to run when the thread is in this state. When a thread lies
in the new state, its code is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In
this state, a thread might actually be running or it might be ready to run at
any instant of time.
3. Blocked/Waiting state: When a thread is temporarily inactive, then it’s in
one of the following states:
 Blocked
 Waiting
4. Timed Waiting: A thread lies in a timed waiting state when it calls a method
with a time-out parameter. A thread lies in this state until the timeout is
completed or until a notification is received. For example, when a thread
calls sleep or a conditional wait, it is moved to a timed waiting state.
5. Terminated State: A thread terminates because of either of the following
reasons:
 Because it exits normally. This happens when the code of the thread has
been entirely executed by the program.
 Because there occurred some unusual erroneous event, like segmentation
fault or an unhandled exception.

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}

Darshan P R, Asst. Professor Page 3


JAVA –Unit4 PESIAMS,Shimoga

Output:
thread is running...

2) Java Thread Example by implementing Runnable


interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnabl
e r)
t1.start();
}
}

Output:
thread is running...

Synchronization in Java
Synchronization in Java is the capability to control the access of multiple
threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread
to access the shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.

Darshan P R, Asst. Professor Page 4


JAVA –Unit4 PESIAMS,Shimoga

2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

f you declare any method as synchronized, it is known as


synchronized method.

Synchronized method is used to lock an object for any shared


resource.

When a thread invokes a synchronized method, it automatically


acquires the lock for that object and releases it when the thread
completes its task.

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){

Darshan P R, Asst. Professor Page 5


JAVA –Unit4 PESIAMS,Shimoga

t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

Darshan P R, Asst. Professor Page 6


JAVA –Unit4 PESIAMS,Shimoga

ava Exception Keywords


Java provides five keywords that are used to handle the exception.
The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place
an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies


that there may occur an exception in the method. It doesn't throw
an exception. It is always used with method signature.

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{System.out.println(e);}
Finally{
System.out.println("rest of the code...");
}} }

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

Darshan P R, Asst. Professor Page 7


JAVA –Unit4 PESIAMS,Shimoga

rest of the code...


Unit 4 Multithreading in Java

Collections in Java:

The Collection in Java is a framework that provides an architecture to store and


manipulate the group of objects.. Java collections can achieve all the operations that
you perform on a data such as searching, sorting, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, vectors,
LinkedList, PriorityQueue,HashSet,LinkedHashSet, TreeSet).

Collection has following parts:

1. Set of interfaces
Interfaces allow collections to be manipulated independently of the details
of their representations.
2. Concrete class implementation of the interfaces.
They are reusable.
3. Standard utility methods and algorithms.

Advantages of java collections:

1. Reduced programming effort


2. Increase quality and speed
3. Reduce effort to learn new API
4. Reduce the effort to design and implement new API.

Collections Hierarchy:

The java.util package contains all the classes and interfaces for the Collection
framework.

Darshan P R, Asst. Professor Page 8


JAVA –Unit4 PESIAMS,Shimoga

Collection Interface:
 The Collection interface is the foundation upon which the Collections Framework
is built because it must be implemented by any class that defines a collection.
Collection is a generic interface that has this declaration.

interface Collection < E >

 Here E specifies the type of objects that the collection will hold. Collection
extends the Iterable interface. This means that all collections can be cycled
through by use of the for-each style for loop.

Methods of Collection interface:

There are many methods declared in the Collection interface. They are as
follows:

No. Method Description

1 public booleanadd(E e) It is used to insert an element in this


collection.

2 public booleanaddAll(Collection<? It is used to insert the specified collection

Darshan P R, Asst. Professor Page 9


JAVA –Unit4 PESIAMS,Shimoga

extends E> c) elements in the invoking collection.

3 public booleanremove(Object element) It is used to delete an element from the


collection.

4 public booleanremoveAll(Collection<?> It is used to delete all the elements of the


c) specified collection from the invoking
collection.

5 default booleanremoveIf(Predicate<? It is used to delete all the elements of the


super E> filter) collection that satisfy the specified predicate.

6 public booleanretainAll(Collection<?> c) It is used to delete all the elements of


invoking collection except the specified
collection.

7 public int size() It returns the total number of elements in the


collection.

8 public void clear() It removes the total number of elements from


the collection.

9 public booleancontains(Object element) It is used to search an element.

10 public booleancontainsAll(Collection<?> It is used to search the specified collection in


c) the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T>T[] toArray(T[] a) It converts collection into array. Here, the


runtime type of the returned array is that of
the specified array.

14 public booleanisEmpty() It checks if collection is empty.

Darshan P R, Asst. Professor Page 10


JAVA –Unit4 PESIAMS,Shimoga

15 default Stream<E>parallelStream() It returns a possibly parallel Stream with the


collection as its source.

16 default Stream<E>stream() It returns a sequential Stream with the


collection as its source.

17 default Spliterator<E>spliterator() It generates a Spliterator over the specified


elements in the collection.

18 public booleanequals(Object element) It matches two collections.

19 public int hashCode() It returns the hash code number of the


collection

Iterator interface:
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface:

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public It returns true if the iterator has more elements otherwise it


booleanhasNext() returns false.

2 public Object next() It returns the element and moves the cursor pointer to the next
element.

3 public void remove() It removes the last elements returned by the iterator. It is less

Darshan P R, Asst. Professor Page 11


JAVA –Unit4 PESIAMS,Shimoga

used.

Iterable Interface:

The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface:

The Collection interface is the interface which is implemented by all the classes
in the collection framework. It declares the methods that every collection will have. In
other words, we can say that the Collection interface builds the foundation on which the
collection framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the
subclasses of Collection interface.

1. List Interface:

 List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values.

 List interface is implemented by the classes ArrayList, LinkedList, Vector, and


Stack.

Darshan P R, Asst. Professor Page 12


JAVA –Unit4 PESIAMS,Shimoga

 There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.

 To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

The classes that implement the List interface are given below.

 ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store
the duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed

 LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no shifting
is required.

 Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.

Darshan P R, Asst. Professor Page 13


JAVA –Unit4 PESIAMS,Shimoga

 Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides its
methods like booleanpush(), boolean peek(), boolean push(object o), which defines its
properties.

2. Queue Interface

 Queue interface maintains the first-in-first-out order. It can be defined as an


ordered list that is used to hold the elements which are about to be
processed.

 There are various classes like PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.

 Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are
given below.

 PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.

 Deque Interface

Darshan P R, Asst. Professor Page 14


JAVA –Unit4 PESIAMS,Shimoga

Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us
to perform the operations at both the ends.

 ArrayDeque:

ArrayDeque class implements the Deque interface. It facilitates us to use the


Deque. Unlike queue, we can add or delete the elements from both the
ends.ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.

3. Set Interface
 Set Interface in Java is present in java.util package. It extends the Collection
interface. It represents the unordered set of elements which doesn't allow us to
store the duplicate items.
 We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
 Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

 HashSet

HashSet class implements Set Interface. It represents the collection that uses a
hash table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.

 LinkedHashSet

Darshan P R, Asst. Professor Page 15


JAVA –Unit4 PESIAMS,Shimoga

LinkedHashSet class represents the LinkedList implementation of Set Interface. It


extends the HashSet class and implements Set interface. Like HashSet, It also contains
unique elements. It maintains the insertion order and permits null elements.

4.SortedSet Interface

o SortedSet is the alternate of Set interface that provides a total ordering on


its elements. The elements of the SortedSet are arranged in the
increasing (ascending) order.

o The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.

 The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

 TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.

Introduction to Java Beans and Network Programming

Java Beans:

 Java beans is an object oriented programming interface from Sun Microsystem


that lets you build reusable applications or program building blocks called that
can be deployed in a network on any major operating system.

Darshan P R, Asst. Professor Page 16


JAVA –Unit4 PESIAMS,Shimoga

 Beans are developed with the Bean Development Kit(BDK) from sun and can be
run on any major operating system platform inside a number of application
environment.

 Java beans are reusable software component for java. They are classes that
encapsulates many objects into a single object. A bean may be visible to an end
user.

 A JavaBean is a Java class that should follow the following conventions:


1. It should have a no-arg constructor.
2. It should be Serializable.
3. It should provide methods to set and get the values of the properties, known as
getter and setter methods.

Why use JavaBean?

According to Java white paper, it is a reusable software component. A bean


encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.

Simple example of JavaBean class:

//Employee.java

package mypack;
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}

Darshan P R, Asst. Professor Page 17


JAVA –Unit4 PESIAMS,Shimoga

How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

JavaBean Properties:

A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features


are accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.

Advantages of JavaBean:

The following are the advantages of JavaBean:/p>

Darshan P R, Asst. Professor Page 18


JAVA –Unit4 PESIAMS,Shimoga

1. The JavaBean properties and methods can be exposed to another application.


2. It provides an easiness to reuse the software components.

Disadvantages of JavaBean:

The following are the disadvantages of JavaBean:

1. JavaBeans are mutable. So, it can't take advantages of immutable objects.


2. Creating the setter and getter method for each property separately may lead to
the boilerplate code.

Network Programming:

 Java Networking is a concept of connecting two or more computing devices


together so that we can share resources.

 Java socket programming provides facility to share data between different


computing devices.

 Advantage of Java Networking

1. Sharing resources
2. Centralize software management

The java.net package supports two protocols,

Darshan P R, Asst. Professor Page 19


JAVA –Unit4 PESIAMS,Shimoga

1. TCP: Transmission Control Protocol provides reliable communication between


the sender and receiver. TCP is used along with the Internet Protocol referred as
TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes

Java Networking Terminology

The widely used Java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address:

 IP address is a unique number assigned to a node of a network e.g.


192.168.0.1 . It is composed of octets that range from 0 to 255.

 It is a logical address that can be changed.

2) Protocol:

 A protocol is a set of rules basically that is followed for communication. For


example:

1. TCP
2. FTP

Darshan P R, Asst. Professor Page 20


JAVA –Unit4 PESIAMS,Shimoga

3. Telnet
4. SMTP
5. POP etc.

3) Port Number:

 The port number is used to uniquely identify different applications. It acts as a


communication endpoint between applications.

 The port number is associated with the IP address for communication between
two applications.

4) MAC Address:

 MAC (Media Access Control) address is a unique identifier of NIC (Network


Interface Controller). A network node can have multiple NIC but each with unique
MAC address.

 For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol

 In connection-oriented protocol, acknowledgement is sent by the receiver. So it is


reliable but slow. The example of connection-oriented protocol is TCP.

 But, in connection-less protocol, acknowledgement is not sent by the receiver. So


it is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket

 A socket is an endpoint between two way communications.

java.net package

The java.net package can be divided into two sections:

Darshan P R, Asst. Professor Page 21


JAVA –Unit4 PESIAMS,Shimoga

1. A Low-Level API: It deals with the abstractions of addresses i.e. networking


identifiers, Sockets i.e. bidirectional data communication mechanism and
Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e.
connections to the resource pointed by URLs.

The java.net package provides many classes to deal with networking applications in
Java.

A list of these classes is given below:

1. Authenticator
2. CacheRequest
3. CacheResponse
4. ContentHandler
5. CookieHandler
6. CookieManager
7. DatagramPacket
8. DatagramSocket
9. DatagramSocketImpl
10. InterfaceAddressetc….

List of interfaces available in java.net package:

1. ContentHandlerFactory
2. CookiePolicy
3. CookieStore
4. DatagramSocketImplFactory
5. FileNameMap
6. SocketOption<T>

Darshan P R, Asst. Professor Page 22


JAVA –Unit4 PESIAMS,Shimoga

7. SocketOptions
8. SocketImplFactory
9. URLStreamHandlerFactory
10. ProtocolFamily

Darshan P R, Asst. Professor Page 23

You might also like