Sie sind auf Seite 1von 23

* Features of Java

Simple
According to Sun, Java language is simple because:
Syntax is based on C++ (so easier for programmers to learn it after C+
+).
Removed many confusing and/or rarely-used features e.g., explicit
pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic
Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplify
software development and maintenance by providing some rules.
Platform Independent
A platform is the hardware or software environment in which a program
runs. There are two types of platforms software-based and hardwarebased. Java provides software-based platform. The Java platform differs
from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms. It has two
components:
Runtime Environment
API(Application Programming Interface)
java is platform independent Java code can be run on multiple
platforms e.g.Windows, Linux, Sun Solaris, Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode
is a platform independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere (WORA).
Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
how java is secured
how java is secured
Classloader- adds security by separating the package for the classes of
the local file system from those that are imported from network
sources.
Bytecode Verifier- checks the code fragments for illegal code that can
violate access right to objects.
Security Manager- determines what resources a class can access such
as reading and writing to the local disk.

These security are provided by java language. Some security can also
be provided by application developer through SSL, JAAS, cryptography
etc.

Robust
Robust simply means strong. Java uses strong memory management.
There are lack of pointers that avoids security problem. There is
automatic garbage collection in java. There is exception handling and
type checking mechanism in java. All these points makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive
types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close"
to native code still somewhat slower than a compiled language (e.g.,
C++)

Distributed
We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the
methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it
shares the same memory. Threads are important for multi-media, Web
applications etc.

*Object
An entity that has state and behavior is known as an object e.g. chair,
bike, marker, pen, table, car etc. It can be physical or logical.
Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from
which objects are created.
Object is a physical entity.
*Class

A class is a group of objects that has common properties.


It is a template or blueprint from which objects are created.
Class is a logical entity.
A class in java can contain:
1. data member
2. method
3. constructor
4. block
5. class and interface

*Constructor
Constructor in java is a special type of method that is used to initialize
the object.
Java constructor is invoked at the time of object creation. It constructs
the values i.e. provides data for the object that is why it is known as
constructor.
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
*Encapsulation
Encapsulation in java is a process of wrapping code and data together
into a single unit.
for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data
members of the class private. Now we can use setter and getter
methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
By providing only setter or getter method, you can make the class
read-only or write-only.
It provides you the control over the data. Suppose you want to set the
value of id i.e. greater than 100 only, you can write the logic inside the
setter method.
*Inheritance (is-a relationship)
Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
Inheritance represents the IS-A relationship, also known as parent-child
relationship.
In the terminology of Java, a class that is inherited is called a super
class. Entertainment
The new class is called a subclass.
Extend keyword is used for inheritance.

Why multiple inheritance is not supported in java?


To
reduce the complexity and simplify the language, multiple inheritance
is not supported in java. multiple inheritance is not supported in case
of class. But it is supported in case of interface because there is no
ambiguity as implementation is provided by the implementation class.
*Aggregation ( has-a relationship)
If a class have an entity reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.
For Code Reusability.
Consider a situation, Employee object contains many informations such
as id, name, emailId etc. It contains one more object named address,
which contains its own informations such as city, state, country,
zipcode etc. as given below:
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
*Method Overloading
If a class have multiple methods by same name but different
parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Method overloading increases the readability of the program its an
advantage.
Method overloading is used for compile polymorphism
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
Why Method Overloaing is not possible by changing the return type of
method?
In java, method overloading is not possible by changing
the return
type of the method because there may occur ambiguity. Let's see how
ambiguity may occur:
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error

}
}
int result=obj.sum(20,20); //Here how can java determine which sum()
method should be called.
*Method Overriding
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding:
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
*Upcasting
When reference variable of Parent class refers to the object of Child
class, it is known as upcasting.
class A{}
class B extends A{}
A a=new B();//upcasting
*Downcasting

*Polymorphism
When one task is performed by different ways i.e. known as
polymorphism.
In java, we use method overloading and method overriding to achieve
polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
There are two types of polymorphism in java: compile time
polymorphism and runtime polymorphism.
Example :
to convense the customer differently, to draw something e.g. shape or
rectangle
*Compiletime Polymorphism ( static Polymorphism)
The process in which a call to the overloaded function resolved at
comppile time is konwn as Compiletime ploymorphism.

*Runtime Polymorphism (Dynamic Polymorphism)


The process in which a call to the overrided function resolved at
comppile time is konwn as Compiletime ploymorphism.
In this example, we are creating two classes Bike and Splendar.
Splendar class extends Bike class and overrides its run() method. We
are calling the run method by the reference variable of Parent class.
Since it refers to the subclass object and subclass method overrides
the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is
known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run();
}
}
O/P : running safely with 60km.
Method is overridden not the datamembers, so runtime polymorphism
can't be achieved by data members.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
O/P: 90
*Abstraction
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
Another way, it shows only important things to the user and hides the
internal details.

for example sending sms, you just type the text and send the
message. You don't know the internal processing about the message
delivery.
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
*Abstract Class
A class that is declared with abstract keyword, is known as abstract
class in java.
It can have abstract and non-abstract methods (method with body).
It needs to be extended and its method implemented.
It cannot be instantiated. means we cant write new A();
extend keyword is used for inheritance.
*Abstract Method
A method that is declared as abstract and does not have
implementation is known as abstract method.
*Interface
An interface in java is a blueprint of a class.
It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction.
It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
implements keyword is used for inheritance.
In other words, Interface fields are public, static and final bydefault,
and methods are public and abstract.
*Marke or Tagged Interface
An interface that have no member is known as marker or tagged
interface. For example: Serializable, Cloneable, Remote etc.
*Multiple inheritance is not supported through class in java but it is
possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance


is not supported in case of class. But it is supported in case of interface
because there is no ambiguity as implementation is provided by the
implementation class.
*Differance between Abstract class & Interface
1) Abstract class can have abstract and non-abstract methods.
Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritance.

Interface supports multiple inheritance.


3) Abstract class can have final, non-final, static and non-static
variables.
Interface has only static and final variables.
4) Abstract class can have static methods, main method and
constructor.
Interface can't have static methods, main method or constructor.
5) Abstract class can provide the implementation of interface.
Interface can't provide the implementation of abstract class.
6) The abstract keyword is used to declare abstract class.
The interface keyword is used to declare interface.
7) Abstract Class Example:
public class Shape{
public abstract void draw();
}
Interface Example:
public interface Drawable{
void draw();
}
* Final Keyword In Java
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
1. Java final variable
a. If you make any variable as final, you cannot change the
value of final variable(It will be constant).
b. Blank or uninitilized final variable
A final variable that is not initialized at the time of
declaration is known as blank final variable.
Can we initialize blank final variable?
Yes, but only in constructor.
static blank final variable

A static final variable that is not initialized at the time of


declaration is known as static blank final variable. It can be
initialized only in static block.
What is final parameter?
If you declare any parameter as final, you cannot change
the value of it.
1. Java Final Method
a. If you make any method as final, you cannot override it.
b. Is final method inherited?
Yes, final method is inherited but you cannot override it.
1. Java Final Class
a. If you make any class as final, you cannot extend it.
*String Class
In java, string objects are immutable. Immutable simply means un-modifiable
or unchangeable.
Once string object is created its data or state can't be changed but a
new string object is created.

Let's try to understand the immutability concept by the example given


below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the en
d
System.out.println(s);//will print Sachin because strings are immutabl
e objects
}
}
O/P : Sachin
Two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
* * Why string objects are immutable in java?

Because java uses the concept of string literal. Suppose there are 5

reference variables, all referes to one object "sachin".If one reference


variable changes the value of the object, it will be affected to all the
reference variables. That is why string objects are immutable in java.
* StringBuffer
Java StringBuffer class is used to created mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is
mutable i.e. it can be changed.
A string that can be modified or changed is known as mutable string.
StringBuffer is synchronized i.e. thread safe. It means two threads can't
call the methods of StringBuffer simultaneously.
StringBuffer is less efficient than StringBuilder.
* StringBuilder
Java StringBuilder class is used to create mutable (modifiable) string.
It is available since JDK 1.5.
StringBuilder is non-synchronized i.e. not thread safe. It means two
threads can call the methods of StringBuilder simultaneously.
StringBuilder is more efficient than StringBuffer.
How to create Immutable class?
There are many immutable classes like String, Boolean, Byte, Short,
Integer, Long, Float, Double etc. In short, all the wrapper classes and
String class is immutable.
We can also create immutable class by creating final class that have
final data members as the example given below:
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}

The above class is immutable because:


The instance variable of the class is final i.e. we cannot change the
value of it after creating an object.

The class is final so we cannot create the subclass.


There is no setter methods i.e. we have no option to change the value
of the instance variable.
These points makes this class as immutable.

* StringTokenizer
The java.util.StringTokenizer class allows you to break a string into
tokens. It is simple way to break string.
Ex 1.
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Ex 2.
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
* Java Regex
The Java Regex or Regular Expression is an API to define pattern for
searching or manipulating strings.
Java Regex API provides 1 interface and 3 classes in java.util.regex
package.
1.
2.
3.
4.

MatchResult interface
Matcher class
Pattern class
PatternSyntaxException class

Matcher Class implements MatchResult interface. It is a regex engine i.e.


used to perform match operations on a character sequence.
It provide three methods:
a) boolean matches() test whether the regular expression matches
the pattern.
b) boolean find() finds the next expression that matches the pattern.
c) boolean find(int start)
finds the next expression that matches
the pattern from the given start number.
Pattern Class is the compiled version of a regular expression. It is used to
define a pattern for the regex engine.
It provide five methods:

a) static Pattern compile(String regex)


compiles the given regex and
return the instance of pattern.
b) Matcher matcher(CharSequence input)
creates a matcher that
matches the given input with pattern.
c) static boolean matches(String regex, CharSequence input)
It
works as the combination of compile and matcher methods. It
compiles the regular expression and matches the given input with
the pattern.
d) String[] split(CharSequence input)
splits the given input string
around matches of given pattern.
e) String pattern()
returns the regex pattern.
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();
//2nd way
boolean b2=Pattern.compile(".s").matcher("as").matches();
//3rd way
boolean b3 = Pattern.matches(".s", "as");
* Serialization
Serialization in java is a mechanism of writing the state of an object
into a byte stream.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implements
java.io.Serializable interface by default.
It is mainly used to travel object's state on the network (known as
marshaling).
java.io.Serializable interface
a) Serializable is a marker interface (has no body). It is just used to
"mark" java classes which support a certain capability.
b) It must be implemented by the class whose object you want to
persist
c) If a class has a reference of another class, all the references
must be Serializable otherwise serialization process will not be
performed. In such case, NotSerializableException is thrown at
runtime.
d) If there is any static data member in a class, it will not be
serialized because static is the part of class not object.

Java Transient Keyword


a) Java transient keyword is used in serialization. If you define any
data member as transient, it will not be serialized.
b) If you deserialize the object, you will get the default value for
transient variable.

* Exception
The exception handling in java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can be
maintained.
Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal
flow of the application. Exception normally disrupts the normal flow of
the application that is why we use exception handling.
Types of Exception
a) There are mainly two types of exceptions: checked and
unchecked where error is considered as unchecked exception.
The sun microsystem says there are three types of exceptions:
1) Checked Exception
2) Unchecked Exception
3) Error

Checked Exception
a)The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions
b)e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.

Uncheked Exception
1) The classes that extend RuntimeException are known as
unchecked exceptions
2) e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
3) Unchecked exceptions are not checked at compile-time rather
they are checked at runtime.

Error
a) Error is irrecoverable
b) e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Handling Keywords


1. There are 5 keywords used in java exception handling.
try, catch, finally, throw, throws
a) Try & Catch
a. Java try block is used to enclose the code that might throw
an exception.
b. It must be used within the method.
c. Java try block must be followed by either catch or finally
block.
d. If you have to perform different tasks at the occurrence of
different Exceptions, use java multi catch block.
e. At a time only one Exception is occured and at a time only
one catch block is executed.
f. All catch blocks must be ordered from most specific to
most general i.e. catch for ArithmeticException must come
before catch for Exception.
g. The try block within a try block is known as nested try
block in java.
h. Sometimes a situation may arise where a part of a block
may cause one error and the entire block itself may cause
another error. In such cases, exception handlers have to be
nested.
b) Finally
a. ava finally block is a block that is used to execute
important code such as closing connection, stream etc.
b. Java finally block is always executed whether exception is
handled or not.
c. Java finally block must be followed by try or catch block.
d. Finally block in java can be used to put "cleanup" code
such as closing a file, closing connection etc.
e. For each try block there can be zero or more catch blocks,
but only one finally block.
f. The finally block will not be executed if program
exits(either by calling System.exit() or by causing a fatal
error that causes the process to abort).
c) throw
a. The Java throw keyword is used to explicitly throw an
exception.
b. We can throw either checked or uncheked exception in java
by throw keyword. The throw keyword is mainly used to
throw custom exception.
c. Throw is followed by an instance.

d. Ex. throw new IOException("sorry device error);


d) throws
a. The Java throws keyword is used to declare an exception.
b. It gives an information to the programmer that there may
occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow
can be maintained.
c. Now Checked Exception can be propagated (forwarded in
call stack).
d. It provides information to the caller of the method about
the exception.
e. If you are calling a method that declares an exception, you
must either caught or declare the exception.
f. Throws is followed by class.
g. Throws is used with the method signature.
h. You can declare multiple exceptions
i. e.g. public void method()throws IOException,SQLException.

Java Exception propagation


An exception is first thrown from the top of the stack and if it is
not caught, it drops down the call stack to the previous method, If
not caught there, the exception again drops down to the previous
method, and so on until they are caught or until they reach the very
bottom of the call stack. This is called exception propagation.
By default Unchecked Exceptions are forwarded in calling chain
(propagated).
By default, Checked Exceptions are not forwarded in calling chain
(propagated).

ExceptionHandling with MethodOverriding in Java


1. There are many rules if we talk about methodoverriding with
exception handling.
2. The Rules are as follows:
a) If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it
can declare unchecked exception.
b) If the superclass method declares an exception, subclass
overridden method can declare same, subclass exception or no
exception but cannot declare parent exception.

* Difference between final, finally and finalize

No. Final

finally

finalize

1
)

Final is used to apply


restrictions on class,
method and variable.
Final class can't be
inherited, final method
can't be overridden and
final variable value can't
be changed.

Finally is used to
place important code,
it will be executed
whether exception is
handled or not.

Finalize is used to
perform clean up
processing just before
object is garbage
collected.

2
)

Final is a keyword.

Finally is a block.

Finalize is a method.

* Multithreading In Java

Multithreading in java is a process of executing multiple threads


simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of
processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
But we use multithreading than multiprocessing because threads share
a common memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less
time than process.
It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
You can perform many operations together so it saves time.
Threads are independent so it doesn't affect other threads if exception
occur in a single thread.
Multitasking

Multitasking is a process of executing multiple tasks


simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
a. Process-based Multitasking(Multiprocessing)
1. Each process have its own address in memory i.e. each
process allocates separate memory area.
2. Process is heavyweight.
3. Cost of communication between the process is high.
4. Switching from one process to another require some time
for saving and loading registers, memory maps, updating
lists etc.
b. Thread-based Multitasking(Multithreading)
1. Threads share the same address space.
2. Thread is lightweight.
3. Cost of communication between the thread is low.
4. At least one process is required for each thread.

Thread
a) A thread is a lightweight sub process, a smallest unit of
processing.
b) It is a separate path of execution.
c) Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads.
d) It shares a common memory area.
e) Life cycle of a Thread
1) The life cycle of the thread in java is controlled by
JVM.
2) The java thread states are as follows:
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.
f) How to create thread
There are two ways to create a thread:
1) By extending Thread class
2) By implementing Runnable interface.
A.
B.
C.

D.
E.
F.
G.
H.
I.
J.
K.
L.
M.
N.
O.

Commonly used methods of Thread class:


public void run(): is used to perform action for a
thread.
public void start(): starts the execution of the
thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily
cease execution) for the specified number of
milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread
to die for the specified miliseconds.
public int getPriority(): returns the priority of the
thread.
public int setPriority(int priority): changes the priority
of the thread.
public String getName(): returns the name of the
thread.
public void setName(String name): changes the
name of the thread.
public Thread currentThread(): returns the reference
of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of
the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing
thread object to temporarily pause and allow other
threads to execute.
public void suspend(): is used to suspend the
thread(depricated).

P. public void resume(): is used to resume the


suspended thread(depricated).
Q. public void stop(): is used to stop the
thread(depricated).
R. public boolean isDaemon(): tests if the thread is a
daemon thread.
S. public void setDaemon(boolean b): marks the thread
as daemon or user thread.
T. public void interrupt(): interrupts the thread.
U. public boolean isInterrupted(): tests if the thread has
been interrupted.
V. public static boolean interrupted(): tests if the
current thread has been interrupted.
g) Priority of a Thread
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
h) Daemon Thread in Java
1. Daemon thread in java is a service provider thread
that provides services to the user thread.
2. Its life depend on the mercy of user threads i.e. when
all the user threads dies, JVM terminates this thread
automatically.
3. There are many java daemon threads running
automatically e.g. gc, finalizer etc.
4. It provides services to user threads for background
supporting tasks.
5. It has no role in life than to serve user threads.
6. Its life depends on user threads.
7. It is a low priority thread.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for
java daemon thread.

1)public void setDaemon(boolean status) is used to


mark the current thread as daemon thread or user
thread.
2)public boolean isDaemon() is used to check that
current is daemon.
* Synchronization
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.
There are two types of thread synchronization mutual exclusive and
inter-thread communication.
A. Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
B. Cooperation (Inter-thread communication in java)

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.
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
o Synchronized block is used to lock an object for any shared
resource.
o Scope of synchronized block is smaller than the method.
If you make any static method as synchronized, the lock will be on the
class not on object.

* Deadlock
Deadlock in java is a part of multithreading. Deadlock can occur in a
situation when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other
to release the lock, the condition is called deadlock.

Inter-thread communication in Java


a. Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
b. Cooperation (Inter-thread communication) is a mechanism in
which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical
section to be executed. It is implemented by following methods
of Object class:
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be
called from the synchronized method only otherwise it will throw
exception.
public final void wait()throws InterruptedException
waits until
object is notified.
public final void wait(long timeout)throws InterruptedException
waits for the specified amount of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to
be awakened. The choice is arbitrary and occurs at the discretion
of the implementation. Syntax:
public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

* Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is
invoked), calling the interrupt() method on the thread, breaks out the
sleeping or waiting state throwing InterruptedException.
If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt
the thread but sets the interrupt flag to true.
In this example, after interrupting the thread, we are propagating it, so
it will stop working. If we don't want to stop the thread, we can handle
it where sleep() or wait() method is invoked.
In this example, after interrupting the thread, we handle the exception
(using try catch block), so it will break out the sleeping but will not stop
working.
* Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait()

sleep()

wait() method releases the


lock

sleep() method doesn't release


the lock.

is the method of Object


class

is the method of Thread class

is the non-static method

is the static method

is the non-static method

is the static method

should be notified by
notify() or notifyAll()
methods

after the specified amount of


time, sleep is completed.

* Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
To do so, we were using free() function in C language and delete() in
C++. But, in java it is performed automatically. So, java provides better
memory management.
Advantage of Garbage Collection
1. It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
2. It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:

o By nulling the reference


o By assigning a reference to another
o By annonymous object etc.
The Garbage collector of JVM collects only those objects that are
created by new keyword. So if you have created any object without
new, you can use finalize method to perform cleanup processing
(destroying remaining objects).
Garbage collection is performed by a daemon thread called Garbage
Collector (GC). This thread calls the finalize() method before object is
garbage collected.

Das könnte Ihnen auch gefallen