java.lang.ClassCastException: Creating a synchronized Linked List

半腔热情 提交于 2019-12-24 13:00:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!