Why does the following code throw CloneNotSupportedException in JDK7 but NOT in JDK6?
public class DemoThread extends Thread implements Cloneable {
/**
* @param args
*/
public static void main(String[] args) {
DemoThread t = new DemoThread();
t.cloned();
}
public DemoThread cloned()
{
try {
return (DemoThread) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
How to Handle CloneNotSupportedException. To avoid the CloneNotSupportedException , the Cloneable interface should be implemented by the class whose objects need to be cloned. This indicates to the Object. clone() method that it is legal to create a clone of that class and helps avoid the CloneNotSupportedException .
Cloneable interface is implemented by a class to make Object. clone() method valid thereby making field-for-field copy. This interface allows the implementing class to have its objects to be cloned instead of using a new operator.
The clone() method of Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class.
A class must implement the Cloneable interface if we want to create the clone of the class object. The clone() method of the Object class is used to create the clone of the object. However, if the class doesn't support the cloneable interface, then the clone() method generates the CloneNotSupportedException.
Here's Thread's implementation of clone()
in SE 7
/**
* Throws CloneNotSupportedException as a Thread can not be meaningfully
* cloned. Construct a new Thread instead.
*
* @throws CloneNotSupportedException
* always
*/
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Threads were never designed to be cloned. Doing some reading sparked off one of the comments I found this summed it up quite well : "But we either have to disallow cloning or give it meaningful semantics - and the latter isn't going to happen." -- David Holmes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With