CloneNotSupportedException even when implementing Cloneable

Why does the following code throw a 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; } } 
+7
source share
2 answers

Here's the clone() thread implementation 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 intended to be cloned. Performing some readings triggered one of the comments that I found, it summed up: "But we either have to prohibit cloning or give it semantic semantics - and the latter will not happen." - David Holmes

+6
source

This does not work because streams cannot be cloned. Line 16 of your code is trying to clone a superclass (Thread) that does not implement the Cloneable interface. Also, cloning a thread is not a good idea. You need to create a new thread. This is the only possible solution here.

+3
source

All Articles