JohnM
JohnM

Reputation: 115

Synchronized collections list

I have 2 threads needing access to a Queue, one for putting and one for getting.

So I have an initiation

public static Queue<WorldData>          blockDestructionQueue   = Collections.synchronizedList(new LinkedList<WorldData>());

With the above I get a Type mismatch: cannot convert from List to Queue

I tried casting it to a Queue but this did not work.

public static Queue<WorldData>          blockDestructionQueue   = (Queue<WorldData>)Collections.synchronizedList(new LinkedList<WorldData>());

I was wondering as to why this is not working.

I got this information from another stack overflow answer.

How to use ConcurrentLinkedQueue?

In the correct answer paragraph 6

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkingQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkingQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Additional Information:

edit: Eclipse was trying to be too helpful and decided to add a break point exception where it was not needed and was not asked to put one.

Upvotes: 1

Views: 984

Answers (2)

Paul
Paul

Reputation: 46

Collections.synchronizedList returns an instance of SynchronizedList which does not extend Queue. LinkedList is a Queue but that's not what you're using at that point.

Upvotes: 0

Chris Cooper
Chris Cooper

Reputation: 5122

A queue is not a list and a Queue is not an implementation of List, although you can implement a queue with a list.

Have a look at BlockingQueue it is probably a better fit for what you need:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html

Upvotes: 2

Related Questions