0% found this document useful (0 votes)
4 views14 pages

Java Unit 2

The document provides an overview of Java Streams, including the differences between InputStream and OutputStream classes, as well as FileInputStream and FileOutputStream. It also covers Java's multithreading capabilities, including thread lifecycle, advantages and disadvantages of multithreaded applications, and synchronization techniques. Additionally, it discusses the use of synchronized methods, blocks, and static synchronization to manage access to shared resources.

Uploaded by

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

Java Unit 2

The document provides an overview of Java Streams, including the differences between InputStream and OutputStream classes, as well as FileInputStream and FileOutputStream. It also covers Java's multithreading capabilities, including thread lifecycle, advantages and disadvantages of multithreaded applications, and synchronization techniques. Additionally, it discusses the use of synchronized methods, blocks, and static synchronization to manage access to shared resources.

Uploaded by

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

Unit-II (Chap-1)

JAVA STREAM
• A stream is a sequence of data, composed of bytes.
• JAVA performs I/O through streams fastly
• java.io package contains the stream classes:- byte stream and character stream
• Can perform java file handling by I/O API
• There are three streams defined in java.lang package:-
1. System.out – Standard output stream
2. System.in – Standard input stream
3. System.err – Standard error stream

INPUTSTREAM VS OUTPUTSTREAM CLASS


INPUTSTREAM OUTPUTSTREAM
Uses input stream to read data. It is an abstract class An abstract class to write data
Superclass of all classes representing an input stream Superclass of all classes representing an output stream
of bytes. of bytes.
Accepts output bytes and sends them to sink.
public abstract int read() public void write(int)
public int available() public void write(byte[])
public void close() public void flush()
public void close()

FILEOUTPUT VS FILEINPUT STREAM


FILEINPUTSTREAM FILEOUTPUTSTREAM
Used to read bytes from a file Used for writing data to file
To read byte-oriented data as well as characted- To write byte-oriented as well as character-oriented data
stream data(FileReader is preferred) (FileWriter is preferred)
public class FileInputStream extends InputStream public class FileOutputStream extends OutputStream
int read(byte[] ary) void write(byte[] ary)
int read (byte[] ary, int off, int len) void write(byte[] ary, int off, int len)
int read() void write(int b)
void close() protected void finalize()
int available (); protected void finalize() void close()
JAVA BYTEARRAYOUTPUTSTREAM CLASS
• used to write common data into multiple files
• data is written into byte array
• public class ByteArrayOutputStream extends OutputStream
• constructors:-
1. ByteArrayOutputStream()
2. ByteArrayOutputStream(int a)

JAVA BYTEARRAYINPUTSTREAM CLASS


• used to read byte array as input stream
• data is read from byte array
• public class ByteArrayInputStream extends InputStream
• constructors:-
3. ByteArrayInputStream(byte array[ ])
4. ByteArrayInputStream(byte array[ ], int off, int len)

JAVA WRITER
• abstract class for writing to character streams
• implements the Closeable, Flushable, and Appendable interfaces

JAVA READER
• abstract class for reading character streams
• implements the Closeable and Readable interfaces

FILEREADER VS FILEWRITER
FILEREADER FILEWRITER
Character-oriented class that reads the Character-oriented class to write
contents from file, returns data in byte character-oriented data into file
form like FileInputStream
Provides method to write string directly
public class FileReader extends public class FileWriter extends
InputStreamReader OutputStreamWriter
int read() void write(char[] c)
void close() void write(char c)
void write(String s)
void close()
void flush()

java.io.CharArrayReader
• creates a character buffer using character array
• constructors:- CharArrayReader(char array[ ])
CharArrayReader(char array[ ], int off, int len)
• public class CharArrayReader extends Reader

java.io.CharArrayWriter
• used to write common data to multiple files
• constructors:- CharArrayWriter( )
CharArrayWriter(int numChars)
• public class CharArrayWriter extends Writer
SERIALIZATION OR OBJECT-SERIALIZATION
• Mechanism of writing the state of an object into a byte-stream
• Mainly used to travel object's state on the network known as marshaling.
• The reverse operation of serialization is called deserialization where byte-stream is converted into an
object.
• After a serialized object is written to a file, it can be read from the file and then deserialized (the
object in memory can be recreated)
• Both are platform-independent
• Serialization - call the writeObject() method ObjectOutputStream class
• Deserialization - call the readObject() method of ObjectInputStream class
• Java Serialization API provides a standard mechanism to handle object serialization. Can only
serialize the objects of a class that implements Serializable interface
• ‘transient’ keyword is used in Object Serialization used with variable declaration
• Used in Hibernate, RMI, JPA, EJB and JMS technologies.

java.io.Serializable interface
• Serializable is a marker interface which has no data member and method
• String class and all wrapper classes implements the java.io.Serializable interface by default
• Cloneable and Remote are some of marker interfaces.

FILTER WRITER CLASS


• Abstract class used to write filtered character streams
• The Subclasses of FilterWriter should override some of these methods and may also provide additional
methods and fields.
• public abstract class FilterWriter extends Writer

FILTER READER CLASS


• Used for reading filtered character streams.
• public abstract class FilterReader extends Reader
• constructor:- protected FilterReader(Reader in) - creates a new filtered reader.
• The class itself provides default methods that pass all requests to the contained stream.
• The Subclasses of FilterReader should override some of these methods and may also provide additional
methods and fields.

PIPED WRITER AND PIPED READER


• PipedWriter class is used to write java pipe as a stream of characters.
• PipedWriter is connected to a PipedReader and used by different threads.
• Constructors:- PipedWriter()
PipedWriter(PipedReader snk)
• PipedReader class is used to read the contents of a pipe as a stream of characters.
• PipedReader class must be connected to the same PipedWriter and are used by different threads.
• Constructors:- PipedReader()
PipedReader(int pipeSize)
PipedReader(PipedWriter src)
PipedReader(PipedWriter src, int pipeSize)
JAVA OUTPUTSTREAM
• Used to write primitive data types and objects to an OutputStream.
• Only object that supports the java.io.Serializable interface can be written to streams.

JAVA INPUTSTREAM
• Deserializes objects and primitive data is written using an ObjectOutputStream
• public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants
Unit-II (Chap-2)
MULTITHREADING
• Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU.
• Each part of such a program is called a thread. So, threads are light-weight processes
within a process.
• a process of executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.

MULTITASKING VS MULTITHREADING

• Multiprocessing and multithreading, both are used to achieve multitasking. They are
high-weighted tasks.
• Each process requires its own separate address space
• Context switching from one process to another is a CPU intensive task needing more
time
• Inter-process communication between processes is again expensive as the
communication mechanism has to span separate address spaces

WHY Threads cost less in terms of processor overhead?


• Multiple threads in a program share the same address space and they are part of the
same process
• A multithreaded application performs two or more activities concurrently
• Switching from one thread to another is less CPU intensive
• Threads are independent
• If there occurs exception in one thread, it doesn't affect other threads.
• Inter-thread communication, on the other hand, is less expensive as threads in a
program communicate within the same address space

LIFE CYCLE OF THREAD

The life cycle of the thread in java is controlled by JVM:- new, runnable, running, non-
runnable and terminated.
• New: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
• Runnable: The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
• Running: The thread is in running state if the thread scheduler has selected it.
• Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently
not eligible to run.
• Terminated: A thread is in terminated or dead state when its run() method exits.

ADVANTAGES OF MULTITHREADED APP


• Reduced number of required servers
• Improved performance and concurrency
• Simplified coding of remote procedure calls and conversations
• Simultaneous access to multiple applications

DISADVANTAGES OF MULTITHREADED APP


• Difficulty of writing code
• Difficulty of debugging
• Difficulty of managing concurrency
• Difficulty of testing
• Difficulty of porting existing code

CREATE THREAD

There are two ways to create a thread:

• By extending Thread class


• By implementing Runnable interface.

THREAD CLASS

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

CONSTRUCTORS OF THREAD CLASS

Thread class extends Object class and implements Runnable interface.

• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
RUNNABLE INTERFACE

• should be implemented by any class whose instances are intended to be executed by a


thread.
• Runnable interface have only one method named run().
• public void run(): is used to perform action for a thread.

START THREAD

start() method of Thread class is used to start a newly created thread. It performs following
tasks:

• A new thread starts(with new callstack).


• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

After starting a thread, it can never be started again. If does so, an IllegalThreadStateException
is thrown.

THREAD CLASS VS RUNNABLE INTERFACE

• If we extend the Thread class, our class cannot extend any other class because Java
doesn’t support multiple inheritance. But, if we implement the Runnable interface, our
class can still extend other base classes.
• We can achieve basic functionality of a thread by extending Thread class because it
provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.

SLEEP METHOD

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
The Thread class provides two methods for sleeping a thread:

• public static void sleep(long miliseconds)throws InterruptedException


• public static void sleep(long miliseconds, int nanos)throws InterruptedException

What if we call run() method directly instead start() method?

• Each thread starts in a separate call stack.


• Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
THE JOIN METHOD

The join() method waits for a thread to die. It causes the currently running threads to stop
executing until the thread it joins with completes its task.

• public void join()throws InterruptedException


• public void join(long milliseconds)throws InterruptedException
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:-

• To prevent thread interference.


• To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization

2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization- mutual exclusive and inter-
thread communication.

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
1. by synchronized method

2. by synchronized block

3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor.


Every object has a lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the


example:

**SEE CODE EXAMPLES FROM JAVA T POINT

A) Java synchronized method

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

What is synchronization in reference to a thread?

->It is a process of handling situations when two or more threads need access to
a shared resource.
Q. A thread can acquire a lock by using which reserved keyword?

-> synchronized

B) Synchronized Block in Java

Synchronized block can be used to perform synchronization on any specific


resource of the method. Suppose you have 50 lines of code in your method, but
you want to synchronize only 5 lines, you can use synchronized block. If you put
all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block

1. Synchronized block is used to lock an object for any shared resource.

2. Scope of synchronized block is smaller than the method.

3. Java synchronized block is more efficient than Java synchronized method.

Syntax to use synchronized block:

synchronized (object reference expression) {

//code block

c) Static Synchronization

If you make any static method as synchronized, the lock will be on the class not
on object.
Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2. In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock. But there can be interference between t1
and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another
lock. I want no interference between t1 and t3 or t2 and t4. Static synchronization
solves this problem.

Example of Static Synchronization

In this example we have used synchronized keyword on the static method to perform
static synchronization.

1. class Table
2. {
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12. class MyThread1 extends Thread{
13. public void run(){
14. Table.printTable(1);
15. }
16. }
17. class MyThread2 extends Thread{
18. public void run(){
19. Table.printTable(10);
20. }
21. }
22. class MyThread3 extends Thread{
23. public void run(){
24. Table.printTable(100);
25. }
26. }
27. class MyThread4 extends Thread{
28. public void run(){
29. Table.printTable(1000);
30. }
31. }
32. public class TestSynchronization4{
33. public static void main(String t[]){
34. MyThread1 t1=new MyThread1();
35. MyThread2 t2=new MyThread2();
36. MyThread3 t3=new MyThread3();
37. MyThread4 t4=new MyThread4();
38. t1.start();
39. t2.start();
40. t3.start();
41. t4.start();
42. }
43. }
44. Output:
45. 1
46. 2
47. 3
48. 4
49. 5
50. 6
51. 7
52. 8
53. 9
54. 10
55. 10
56. 20
57. 30
58. 40
59. 50
60. 60
61. 70
62. 80
63. 90
64. 100
65. 100
66. 200
67. 300
68. 400
69. 500
70. 600
71. 700
72. 800
73. 900
74. 1000
75. 1000
76. 2000
77. 3000
78. 4000
79. 5000
80. 6000
81. 7000
82. 8000
83. 9000
84. 10000

You might also like