How to synchronize access to LinkedList??

T

Tobi Krausl

Hi!

I need a java-implementation of a queue and found out that
java.util.LinkedList is suitable. In my program there are several
threds accessing and maniplating that LinkedList. Consequently I've to
synchronize access to it.

I found the follwing which doesn't work:
http://javaalmanac.com/egs/java.util/coll_Queue.html?l=rel

e342. Implementing a Queue
LinkedList queue = new LinkedList();

queue.add(object);

Object o = queue.removeFirst();

//Here I get a class-cast-exception, why??????
queue = (LinkedList)Collections.synchronizedList(queue);



I always get a class-cast-exception!

What's wrong??

Tnx,
Tobi
 
V

VisionSet

--
Mike W
Tobi Krausl said:
Hi!

I need a java-implementation of a queue and found out that
java.util.LinkedList is suitable. In my program there are several
threds accessing and maniplating that LinkedList. Consequently I've to
synchronize access to it.

I found the follwing which doesn't work:
http://javaalmanac.com/egs/java.util/coll_Queue.html?l=rel

e342. Implementing a Queue
LinkedList queue = new LinkedList();

queue.add(object);

Object o = queue.removeFirst();

//Here I get a class-cast-exception, why??????
queue = (LinkedList)Collections.synchronizedList(queue);



I always get a class-cast-exception!

What's wrong??

If it returned a LinkedList you wouldn't have achieved anything, it returns
an implementation of List that is synchronized. You are just limited to the
List interface.

try:

List queue = new LinkedList();

queue.add(object);

Object o = queue.removeFirst();

queue = (LinkedList)Collections.synchronizedList(queue);
 
M

Michael Borgwardt

Tobi said:
Hi!

I need a java-implementation of a queue and found out that
java.util.LinkedList is suitable. In my program there are several
threds accessing and maniplating that LinkedList. Consequently I've to
synchronize access to it.

Note that this naive synchronizing of method calls will be insufficient
if you iterate over the list or have sequences of calls that depend on
each other.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top