Fork/Join

 

Java multithreading interview questions (java-success.com)

In Java, memory leak can occur due to

1)   Long living objects having reference to short living objects, causing the memory to slowly grow.

For example, singleton classes referring to short lived objects.

This prevents short-lived objects being garbage collected.

2)   Improper use of thread-local variables.

The thread-local variables will not be removed by the garbage collector as long as the thread itself is alive.

So, when threads are pooled and kept alive forever, the object might never be removed by the garbage collector.

3)   Using mutable static fields to hold data caches, and not explicitly clearing them.

The mutable static fields and collections need to be explicitly cleared.

4) Objects with circular references that are reachable from a GC Root object.

 

Q14. What is the disadvantage of synchronization?
A14. The disadvantage of synchronization is that it can cause deadlocks when two threads are

waiting on each other to do something. Also, synchronized code has the overhead of acquiring lock,

and preventing concurrent access, which can adversely affect performance.

 

 

How to avoid deadlock

·       Use ConcurrentHashMap 

·       Avoid nested locks

·       do it in the same order 

·       Use thread pools

·       Java Executor framework for efficiently managing a collection of threads.

·       Use timeouts

 

GraphQL reduces number of Rest APIs

 

 

Concurrency

 

 

Parallel Execution

 

 

 

 

public class DeadLock {

   
public static void main(String[] args) {
       
Integer resource1 = 1;
       
Integer resource2 = 2;
       
Thread thread1 = new Thread() {
           
public void run() {
               
synchronized (resource1) {
                   
System.out.println("Thread 1 locking resource 1");
                   
try {
                       
Thread.sleep(100);
                    }
catch (Exception e) {
                    }
                   
synchronized (resource2) {
                       
System.out.println("Thread 1 locking resource 2");
                    }
                }
            }
        };
       
Thread thread2 = new Thread() {
           
public void run() {
               
synchronized (resource2) {
                   
System.out.println("Thread 2 locking resource 2");
                   
try {
                       
Thread.sleep(100);
                    }
catch (Exception e) {
                    }
                   
synchronized (resource1) {
                       
System.out.println("Thread 2 locking resource 1");
                    }
                }
            }
        };
       
thread1.start();
       
thread2.start();
    }
}

 

Thread 1 locking resource 1

Thread 2 locking resource 2