Messaging

Report a typo

Write a program that simulates a simple message system. Each message has three fields: from, to, and text.

The interface AsyncMessageSender describes an abstraction that can send messages and stop its work.

interface AsyncMessageSender {
    fun sendMessages(messages: List<Message>): Unit
    fun stop(): Unit
}

The class AsyncMessageSenderImpl implements this interface and repeats each message several times (according to a variable).

Complete this class. It should:

  • use ExecutorService to send multiple messages in parallel;
  • implement repeating of messages in the sendMessage function;
  • implement the stop function to shut down the executor and wait until it stops (it means blocking the thread that invokes it).

Here is an example of a testing code that should successfully work with your implementation.

val sender: AsyncMessageSender = AsyncMessageSenderImpl (3)

val messages: List<Message> = listOf(
    Message ("John", "Mary", "Hello!"),
    Message ("Clara", "Bruce", "How are you today?")
)

sender.sendMessages(messages)
sender.stop()

notifyAboutEnd() // it prints something after the sender successfully stops

Here is the output:

(John>Mary): Hello!
(John>Mary): Hello!
(John>Mary): Hello!
(Clara>Bruce): How are you today?
(Clara>Bruce): How are you today?
(Clara>Bruce): How are you today?
Completed.

The order of the sent messages may be different, but the last line must remain the last.

Write a program in Kotlin
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/* Do not change this class */
data class Message(val from: String, val to: String, val text: String)

/* Do not change this interface */
interface AsyncMessageSender {
fun sendMessages(messages: List<Message>)
fun stop()
}

class AsyncMessageSenderImpl(val repeatFactor: Int) : AsyncMessageSender {
val executor: ExecutorService = // TODO initialize the executor

override fun sendMessages(messages: List<Message>) {
for (msg in messages) {
// TODO repeat messages
executor.submit {
println("(${msg.from}>${msg.to}): ${msg.text}") // do not change it
}
}
}

override fun stop() {
// TODO stop the executor and wait for it
}
}
___

Create a free account to access the full topic