Posts Tagged ‘java’

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 »

Java to XML, XML to Java (Marshalling and Unmarshalling)

Wednesday, July 13th, 2011

Introduction

JDK6 and JAXB2.x (which comes with JDK6) make marshalling Java to XML and unmarshalling XML to Java a snap, almost trivial.

Example

Java to XML

package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class JavaToXML {
	public static void main(String[] args) throws Exception {
		JAXBContext context = JAXBContext.newInstance(Product.class);

		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

		Product object = new Product();
		object.setCode("WI1");
		object.setName("Widget Number One");
		object.setPrice(BigDecimal.valueOf(300.00));

		m.marshal(object, System.out);
	}
}

XML to Java

package foo.bar;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XMLToJava {

	public static void main(String[] args) {
		try {
			JAXBContext jc = JAXBContext.newInstance(Product.class);
			Unmarshaller u = jc.createUnmarshaller();

			File f = new File("product.xml");
			Product product = (Product) u.unmarshal(f);

			System.out.println(product.getCode());
			System.out.println(product.getName());
			System.out.println(product.getPrice());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}

product.java

Note: the @XmlRootElement is vital here!

package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
	private String code;
	private String name;
	private BigDecimal price;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public BigDecimal getPrice() {
		return price;
	}
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
}

product.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product>
    <code>WI1</code>
    <name>Widget Number One</name>
    <price>300.0</price>
</product>

Tags: , ,
Posted in Examples | 7 Comments »

Read a File as String with Java

Thursday, June 16th, 2011

Introduction

I’m always Googling for a way to do this. This seems to be the best “idiomatic” solution I’ve found. So without further ado…

Example

public String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try{
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        return Charset.defaultCharset().decode(bb).toString();
    }
    finally {
        stream.close();
    }
}

Tags:
Posted in Development, How to's, quick tips | No Comments »

Unit Test Private Java Methods using Reflection

Thursday, May 5th, 2011

Introduction

I realise that the thought of Unit Testing private methods in Java classes can be like a red rag to a bull for some people and I understand the arguments.

Therefore, I present the following as a “how to”, not a moral argument for or against!

Example

The class under test

public class Product() {
    private String privateMethod(String id) {
    //Do something private
    return "product_" + id;
  }
}

The (Reflection Based) Unit Test

import java.lang.reflect.Method;

import static org.junit.Assert.*;
import org.junit.Test;

public class ProductTest {
    private Product product; // the class under test
    private Method m;
    private static String METHOD_NAME = "privateMethod";
    private Class[] parameterTypes;
    private Object[] parameters;

    @Before
    public void setUp() throws Exception {
        product = new Product();
        parameterTypes = new Class[1];
        parameterTypes[0] = java.lang.String.class;
        m = product.getClass().getDeclaredMethod(METHOD_NAME, parameterTypes);
        m.setAccessible(true);
        parameters = new Object[1];
    }

    @Test
    public void testPrivateMethod() throws Exception {
        parameters[0] = "someIdentifier";
        String result = (String) m.invoke(product, parameters); 
  
        //Do your assertions
        assertNotNull(result);
    }
}

Update

I’ve since been told that if dp4j.jar is in the classpath at compile-time, it will inject the necessary reflection to make this work. I haven’t had time to try this yet so YMMV.

Tags: , ,
Posted in Development, How to's | No Comments »