23
Java Tips Viswanath L

Java tips

Embed Size (px)

DESCRIPTION

Java Advanced Tips

Citation preview

Page 1: Java tips

Java TipsViswanath L

Page 2: Java tips

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

Page 3: Java tips

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)));

Page 4: Java tips

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.

Page 5: Java tips

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.

Page 6: Java tips

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.

Page 7: Java tips

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.

Page 8: Java tips

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.

Page 9: Java tips

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);

}}

Page 10: Java tips

How to create Stackoverflow error?

Private void a() {a();

}

Page 11: Java tips

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.

Page 12: Java tips

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

Page 13: Java tips

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.

Page 14: Java tips

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.

Page 15: Java tips

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.

Page 16: Java tips

private static class Task implements Runnable {private CyclicBarrier cyclicBarrier;// Here a constructor with cyclic barrier as argument@Overridepublic 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(); }

Page 17: Java tips

Output:

Thread 1 is waiting on barrierThread 3 is waiting on barrierThread 2 is waiting on barrierAll threads reached on barrier ==> Lets start workingThread 3 has crossed the barrierThread 1 has crossed the barrierThread 2 has crossed the barrier

Page 18: Java tips

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)

Page 19: Java tips

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 .

Page 20: Java tips

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.

Page 21: Java tips

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.

Page 22: Java tips

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.

Page 23: Java tips

Reference: Google

Thank You