ConcurrentLinkedQueue

I looked in your co-routines v. 0.3 book and couldn’t find anything on
ConcurrentLinkedQueue.

I have 2 libraries from github - one is Kotlin and the other is Java. Both perform well but the java library is more comprehensive.

Kotlin uses the queue with a data class:
private val operationQueue = ConcurrentLinkedQueue()
// operation is a data class
operationQueue.add(operation)

Java uses the queue with a runnable:
@NotNull
private final Queue commandQueue = new ConcurrentLinkedQueue<>();
final boolean result = commandQueue.add(new Runnable() {
@Override
public void run() {

}
});

Both libraries are interfacing to a bluetooth device and queue up the commands/operations for the device using the ConcurrentLinked Queue object. Obviously they are asynchronous operations for sending and receiving to the device.

First question:
I’m confused on why runnable instance is needed in the java library but not the kotlin library.
If ConcurrentLinked Queue is already thread-safe and is using co-routines, why use a runnable?

Second question:
There are a lot of commands and responses being handled.
Is creating a runnable instance each time a command needs to be placed in the queue going to be resource intensive or create any kind of memory problem?

That is because it is not really related to coroutines. :grinning:

A Runnable is not really related to threads. It simply represents a chunk of code to run. You can wrap a Runnable in a Thread, and some thread-related stuff happens to use Runnable, but Runnable itself is not tied to threads. Basically, Runnable was a precursor to the modern lambda expression.

A Runnable is not intrinsically more expensive than is any other object. Specific Runnable objects might be expensive due to objects they capture in their declaration, but that is the same with any other instantiation of an abstract type using a inner class — it is not unique to Runnable.

1 Like