Archive for the ‘Interview Questions’ Category

Java – deliberately cause Deadlock

Tuesday, August 4th, 2015

Another interview question.

When this code is executed runnable1 will wait for a lock on “b” and runnable2 will wait for a lock on “a”.

package test;
/**
 * Deliberately try and cause deadlock
 * 
 */
public class DeadLockTest {
    public static void main(String[] args) {
    	final Object a = new Object();
        final Object b = new Object();
 
        final Runnable runnable1 = new Runnable() {
            public void run() {
                synchronized (a) {
                    try {
                        Thread.sleep(100); // Adding delay to increase chance of deadlock
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    synchronized (b) { // We already have "a" abut need "b" too
                        System.out.println("In runnable1");
                    }
                }
            }
        };
 
        final Runnable runnable2 = new Runnable() {
            public void run() {
                synchronized (b) { // Has "b" but needs "a"
                    synchronized (a) {
                        System.out.println("In runnable2");
                    }
                }
            }
        };
 
        new Thread(runnable1).start();
        new Thread(runnable2).start();
    }
}

Tags:
Posted in Interview Questions | No Comments »

Java – deliberately cause OutOfMemoryException

Tuesday, August 4th, 2015

package test;

import java.util.ArrayList;
import java.util.List;

public class OutOfMemory {
    public static void main(String[] args) {
    	final List<String>list = new ArrayList<String>();
    	int i = 1;
    	while(true) {
			list.add(new String(System.nanoTime()+""));
			list.addAll(list);
			System.out.println(i+ " " + Runtime.getRuntime().freeMemory());
			i++;
		}
    	
    }
}

After a few seconds should output something like:


Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2245)
at java.util.Arrays.copyOf(Arrays.java:2219)
at java.util.ArrayList.grow(ArrayList.java:213)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:187)
at java.util.ArrayList.addAll(ArrayList.java:532)
at test.OutOfMemory.main(OutOfMemory.java:12)

Tags:
Posted in Interview Questions | No Comments »