问题
I want a synchronized LinkedList with a Generic Class A, here the relevant parts:
public abstract class A<T extends B> implements Runnable {
And the interface for B, where the "real" B, will be a supclass
public interface B{
Following setup will throw a runtime error:
LinkedList<A<? extends B>> eopList = (LinkedList<A<? extends B>>) Collections
.synchronizedCollection(new LinkedList<A<? extends B>>());
I've found the following proposal, but it also won't compile:
LinkedList<A<? extends B>> eopList = (LinkedList) Collections
.synchronizedCollection(new LinkedList<A<? extends B>>());
This Is the Log:
Exception in thread "main" java.lang.ClassCastException: java.util.Collections$SynchronizedCollection cannot be cast to java.util.LinkedList
回答1:
Use Collections.synchronizedList() method instead. The method returns a List<T>
. So, make the type on LHS as List
, to avoid typecast:
List<A<? extends B>> eopList = Collections.synchronizedList(new LinkedList<A<? extends B>>());
回答2:
In the words of nos on Is LinkedList thread-safe when I'm accessing it with offer and poll exclusively?:
LinkedList is not thread safe. You'll have to do the locking yourself.
Try ConcurrentLinkedQueue or LinkedBlockingDeque instead if it fits your needs
or try this code from Piyush Hari's answer:
LinkedList<A<? extends B>> eopList = (LinkedList)Collections.synchronizedList(new LinkedList<A<? extends B>());
来源:https://stackoverflow.com/questions/19510360/java-lang-classcastexception-creating-a-synchronized-linked-list