SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Viswanath L
Why String is immutable in java ?
 Do you have any doubt , whether string is immutable ?
 Have you ever tried to extend the String class ?
 Try to do that you will reach to the conclusion - > String is final
 Same for Integer, Float , etc
 String pool requires string to be immutable otherwise shared reference
can be changed from anywhere.
 Security because string is shared on different area like file system,
networking connection, database connection , having immutable
string allows you to be secure and safe because no one can change
reference of string once it gets created. if string had been mutable
anyone can surpass the security be logging in someone else name and
then later modifying file belongs to other.
Same for integer as well, Lets look in to an example
Integer a = 3;
System.out.println("before “ + Integer.toHexString(System.identityHashCode(a)));
a += 3;
System.out.println("after “ + Integer.toHexString(System.identityHashCode(a)));
noclassdeffounderror & classnotfoundexception
For ClassNotFoundException:
Thrown when an application tries to load in a class through its string
name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader.
The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.
As for ClassNotFoundException, it appears that it may stem from
trying to make reflective calls to classes at runtime, but the classes the
program is trying to call does not exist.
For NoClassDefFoundError:
Thrown if the Java Virtual Machine or a ClassLoader instance tries to
load in the definition of a class (as part of a normal method call or as
part of creating a new instance using the new expression) and no
definition of the class could be found.
The searched-for class definition existed when the currently executing
class was compiled, but the definition can no longer be found.
So, it appears that the NoClassDefFoundError occurs when the source
was successfully compiled, but at runtime, the required class files were
not found. This may be something that can happen in the distribution
or production of JAR files, where not all the required class files were
included.
The difference between the two is that one is an Error and the other is
an Exception. With NoClassDefFoundError is an Error and it arises
from the Java Virtual Machine having problems finding a class it
expected to find. A program that was expected to work at compile-time
can't run because of class files not being found, or is not the same as
was produced or encountered at compile-time. This is a pretty critical
error, as the program cannot be initiated by the JVM.
On the other hand, the ClassNotFoundException is an Exception, so it
is somewhat expected, and is something that is recoverable. Using
reflection is can be error-prone (as there is some expectations that
things may not go as expected. There is no compile-time check to see
that all the required classes exist, so any problems with finding the
desired classes will appear at runtime.
Stack and Heap memory
Main difference between heap and stack is that stack memory is used
to store local variables and function call, while heap memory is used to
store objects in Java. No matter, where object is created in code e.g. as
member variable, local variable or class variable, they are always
created inside heap space in Java.
Each Thread in Java has there own stack which can be specified using -
Xss JVM parameter, similarly you can also specify heap size of Java
program using JVM option -Xms and -Xmx where -Xms is starting size
of heap and -Xmx is maximum size of java heap.
If there is no memory left in stack for storing function call or local
variable, JVM will throw java.lang.StackOverFlowError, while if there is
no more heap space for creating object, JVM will throw
java.lang.OutOfMemoryError: Java Heap Space.
If you are using Recursion, on which method calls itself, You can
quickly fill up stack memory. Another difference between stack and
heap is that size of stack memory is lot lesser than size of heap
memory in Java.
Variables stored in stacks are only visible to the owner Thread, while
objects created in heap are visible to all thread. In other words stack
memory is kind of private memory of Java Threads, while heap
memory is shared among all threads.
How to create Out of memory error?
public void createOOM() {
int iterator = 20;
System.out.println("===> Started");
for(int i = 0; i < iterator; i ++) {
System.out.println("Free memory on iteration : " + i + "==>" +
Runtime.getRuntime().freeMemory());
int[] array = new int[iterator];
int filler = i;
do {
array[filler] = 0;
filler--;
} while(filler > 0);
iterator *= 5;
System.out.println("Required memory for next loop: ==>" + iterator);
Thread.sleep(1000);
}
}
How to create Stackoverflow error?
Private void a() {
a();
}
What is Thread in Java?
Thread is an independent path of execution. It's way to take advantage
of multiple CPU available in a machine. By employing multiple threads
you can speed up CPU bound task. For example, if one thread takes 100
millisecond to do a job, you can use 10 thread to reduce that task into 10
millisecond. Java provides excellent support for multi-threading at
language level, and its also one of strong selling point.
When to use Runnable vs Thread in Java?
• Its better to implement Runnable than extends Thread, if you also
want to extend another class e.g. Canvas or CommandListener.
Difference between Thread and Process in Java?
Thread is subset of Process, in other words one process can contain
multiple threads. Two process runs on different memory space, but all
threads share same memory space. Don't confuse this with stack
memory, which is different for different thread and used to store local
data to that thread
Difference between start() and run() method of
Thread class?
start() method is used to start newly created thread, while start()
internally calls run() method, there is difference calling run() method
directly. When you invoke run() as normal method, its called in the
same thread, no new thread is started, which is the case when you call
start() method.
Difference between Runnable and Callable in Java?
Both Runnable and Callable represent task which is intended to be
executed in separate thread. Runnable is there from JDK 1.0, while
Callable was added on JDK 1.5. Main difference between these two is
that Callable's call() method can return value and throw Exception,
which was not possible with Runnable's run() method. Callable return
Future object, which can hold result of computation.
What is CyclicBarrier ?
CyclicBarrier is a natural requirement for concurrent program because
it can be used to perform final part of task once individual tasks are
completed. All threads which wait for each other to reach barrier are
called parties, CyclicBarrier is initialized with number of parties to be
wait and threads wait for each other by
calling CyclicBarrier.await() method which is a blocking method in
java and blocks until all Thread or parties call await(). In general
calling await() is shout out that Thread is waiting on barrier. await() is a
blocking call but can be timed out or Interrupted by other thread.
private static class Task implements Runnable {
private CyclicBarrier cyclicBarrier;
// Here a constructor with cyclic barrier as argument
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + “ has crossed the
barrier");
}
}
public static void main(String a[]) {
final CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
public void run() {
System.out.println("All threads reached on barrier ==> Lets start working"); }});
Thread t1 = new Thread(new Task(cyclicBarrier), "Thread 1");
Thread t2 = new Thread(new Task(cyclicBarrier), "Thread 2");
Thread t3 = new Thread(new Task(cyclicBarrier), "Thread 3");
t1.start();
t2.start();
t3.start();
}
Output:
Thread 1 is waiting on barrier
Thread 3 is waiting on barrier
Thread 2 is waiting on barrier
All threads reached on barrier ==> Lets start working
Thread 3 has crossed the barrier
Thread 1 has crossed the barrier
Thread 2 has crossed the barrier
CyclicBarrier can perform a completion task once all thread reaches to
barrier, This can be provided while creating CyclicBarrier.
If CyclicBarrier is initialized with 3 parties means 3 thread needs to call
await method to break the barrier.
Thread will block on await() until all parties reaches to barrier, another
thread interrupt or await timed out.
If another thread interrupt the thread which is waiting on barrier it
will throw BrokernBarrierException as shown below:
java.util.concurrent.BrokenBarrierException at
java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
CyclicBarrier.reset() put Barrier on its initial state, other thread which
is waiting or not yet reached barrier will terminate
with java.util.concurrent.BrokenBarrierException.
That's all on What is CyclicBarrier in Java , When to use CyclicBarrier
in Java and a Simple Example of How to use CyclicBarrier in Java .
Difference between notify and notifyAll in Java?
There notify() method doesn't provide any way to choose a
particular thread, that's why its only useful when you know that
there is only one thread is waiting. On the other
hand, notifyAll() sends notification to all threads and allows
them to compete for locks, which ensures that at-least one
thread will proceed further.
Why wait, notify and notifyAll are not inside thread class?
Java provides lock at object level not at thread level. Every object
has lock, which is acquired by thread. Now if thread needs to
wait for certain lock it make sense to call wait() on that object
rather than on that thread. Had wait() method declared on
Thread class, it was not clear that for which lock thread was
waiting. In short, since wait, notify and notifyAll operate at lock
level, it make sense to defined it on object class because lock
belongs to object.
Difference between livelock and deadlock in Java?
A livelock is similar to a deadlock, except that the states of the threads
or processes involved in the livelock constantly change with regard to
one another, without any one progressing further. Livelock is a special
case of resource starvation. A real-world example of livelock occurs
when two people meet in a narrow corridor, and each tries to be polite
by moving aside to let the other pass, but they end up swaying from
side to side without making any progress because they both repeatedly
move the same way at the same time. In short, main difference between
livelock and deadlock is that in former state of process change but no
progress is made.
Reference: Google
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaAppsterdam Milan
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPSrithustutorials
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyondRafael Winterhalter
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by ExampleGanesh Samarthyam
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easyRafael Winterhalter
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questionsrithustutorials
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemRafael Winterhalter
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyKing's College London
 
Threading in C#
Threading in C#Threading in C#
Threading in C#Medhat Dawoud
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
Java session13
Java session13Java session13
Java session13Niit Care
 

Was ist angesagt? (20)

Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questions
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystem
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
04 threads
04 threads04 threads
04 threads
 
Java session13
Java session13Java session13
Java session13
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 

Ă„hnlich wie Java tips

Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptxajmalhamidi1380
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questionsMehtaacademy
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdfvenud11
 
Java unit 12
Java unit 12Java unit 12
Java unit 12Shipra Swati
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questionsGradeup
 
Threads in Java
Threads in JavaThreads in Java
Threads in JavaHarshaDokula
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Unit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptxUnit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptxDrYogeshDeshmukh1
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick GuideAnton Shchastnyi
 

Ă„hnlich wie Java tips (20)

Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Unit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptxUnit No 4 Exception Handling and Multithreading.pptx
Unit No 4 Exception Handling and Multithreading.pptx
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
 

KĂĽrzlich hochgeladen

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

KĂĽrzlich hochgeladen (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

Java tips

  • 2. Why String is immutable in java ?  Do you have any doubt , whether string is immutable ?  Have you ever tried to extend the String class ?  Try to do that you will reach to the conclusion - > String is final  Same for Integer, Float , etc
  • 3.  String pool requires string to be immutable otherwise shared reference can be changed from anywhere.  Security because string is shared on different area like file system, networking connection, database connection , having immutable string allows you to be secure and safe because no one can change reference of string once it gets created. if string had been mutable anyone can surpass the security be logging in someone else name and then later modifying file belongs to other. Same for integer as well, Lets look in to an example Integer a = 3; System.out.println("before “ + Integer.toHexString(System.identityHashCode(a))); a += 3; System.out.println("after “ + Integer.toHexString(System.identityHashCode(a)));
  • 4. noclassdeffounderror & classnotfoundexception For ClassNotFoundException: Thrown when an application tries to load in a class through its string name using: The forName method in class Class. The findSystemClass method in class ClassLoader. The loadClass method in class ClassLoader. but no definition for the class with the specified name could be found. As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call does not exist.
  • 5. For NoClassDefFoundError: Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found. So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
  • 6. The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM. On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.
  • 7. Stack and Heap memory Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java. Each Thread in Java has there own stack which can be specified using - Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap.
  • 8. If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space. If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is lot lesser than size of heap memory in Java. Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all thread. In other words stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads.
  • 9. How to create Out of memory error? public void createOOM() { int iterator = 20; System.out.println("===> Started"); for(int i = 0; i < iterator; i ++) { System.out.println("Free memory on iteration : " + i + "==>" + Runtime.getRuntime().freeMemory()); int[] array = new int[iterator]; int filler = i; do { array[filler] = 0; filler--; } while(filler > 0); iterator *= 5; System.out.println("Required memory for next loop: ==>" + iterator); Thread.sleep(1000); } }
  • 10. How to create Stackoverflow error? Private void a() { a(); }
  • 11. What is Thread in Java? Thread is an independent path of execution. It's way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task. For example, if one thread takes 100 millisecond to do a job, you can use 10 thread to reduce that task into 10 millisecond. Java provides excellent support for multi-threading at language level, and its also one of strong selling point. When to use Runnable vs Thread in Java? • Its better to implement Runnable than extends Thread, if you also want to extend another class e.g. Canvas or CommandListener.
  • 12. Difference between Thread and Process in Java? Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. Don't confuse this with stack memory, which is different for different thread and used to store local data to that thread
  • 13. Difference between start() and run() method of Thread class? start() method is used to start newly created thread, while start() internally calls run() method, there is difference calling run() method directly. When you invoke run() as normal method, its called in the same thread, no new thread is started, which is the case when you call start() method.
  • 14. Difference between Runnable and Callable in Java? Both Runnable and Callable represent task which is intended to be executed in separate thread. Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these two is that Callable's call() method can return value and throw Exception, which was not possible with Runnable's run() method. Callable return Future object, which can hold result of computation.
  • 15. What is CyclicBarrier ? CyclicBarrier is a natural requirement for concurrent program because it can be used to perform final part of task once individual tasks are completed. All threads which wait for each other to reach barrier are called parties, CyclicBarrier is initialized with number of parties to be wait and threads wait for each other by calling CyclicBarrier.await() method which is a blocking method in java and blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on barrier. await() is a blocking call but can be timed out or Interrupted by other thread.
  • 16. private static class Task implements Runnable { private CyclicBarrier cyclicBarrier; // Here a constructor with cyclic barrier as argument @Override public void run() { System.out.println(Thread.currentThread().getName() + " is waiting on barrier"); cyclicBarrier.await(); System.out.println(Thread.currentThread().getName() + “ has crossed the barrier"); } } public static void main(String a[]) { final CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() { public void run() { System.out.println("All threads reached on barrier ==> Lets start working"); }}); Thread t1 = new Thread(new Task(cyclicBarrier), "Thread 1"); Thread t2 = new Thread(new Task(cyclicBarrier), "Thread 2"); Thread t3 = new Thread(new Task(cyclicBarrier), "Thread 3"); t1.start(); t2.start(); t3.start(); }
  • 17. Output: Thread 1 is waiting on barrier Thread 3 is waiting on barrier Thread 2 is waiting on barrier All threads reached on barrier ==> Lets start working Thread 3 has crossed the barrier Thread 1 has crossed the barrier Thread 2 has crossed the barrier
  • 18. CyclicBarrier can perform a completion task once all thread reaches to barrier, This can be provided while creating CyclicBarrier. If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier. Thread will block on await() until all parties reaches to barrier, another thread interrupt or await timed out. If another thread interrupt the thread which is waiting on barrier it will throw BrokernBarrierException as shown below: java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172) at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
  • 19. CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException. That's all on What is CyclicBarrier in Java , When to use CyclicBarrier in Java and a Simple Example of How to use CyclicBarrier in Java .
  • 20. Difference between notify and notifyAll in Java? There notify() method doesn't provide any way to choose a particular thread, that's why its only useful when you know that there is only one thread is waiting. On the other hand, notifyAll() sends notification to all threads and allows them to compete for locks, which ensures that at-least one thread will proceed further.
  • 21. Why wait, notify and notifyAll are not inside thread class? Java provides lock at object level not at thread level. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain lock it make sense to call wait() on that object rather than on that thread. Had wait() method declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait, notify and notifyAll operate at lock level, it make sense to defined it on object class because lock belongs to object.
  • 22. Difference between livelock and deadlock in Java? A livelock is similar to a deadlock, except that the states of the threads or processes involved in the livelock constantly change with regard to one another, without any one progressing further. Livelock is a special case of resource starvation. A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time. In short, main difference between livelock and deadlock is that in former state of process change but no progress is made.