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 {
    public void sendMessages(Message[] messages);
    public void stop();
}

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 method;
  • implement the stop method to shut down the executor and wait until it stops (it means it blocks a thread that invokes it).

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


AsyncMessageSender sender = new AsyncMessageSenderImpl(3);
       
Message[] messages = {

    new Message("John", "Mary", "Hello!"),
    new Message("Clara", "Bruce", "How are you today?")
};

sender.sendMessages(messages);
sender.stop();

notifyAboutEnd(); // it prints something after the sender successfully stop

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 Java 17
import java.util.concurrent.*;

/* Do not change this class */
class Message {
final String text;
final String from;
final String to;

Message(String from, String to, String text) {
this.text = text;
this.from = from;
this.to = to;
}
}

/* Do not change this interface */
interface AsyncMessageSender {
void sendMessages(Message[] messages);
void stop();
}

class AsyncMessageSenderImpl implements AsyncMessageSender {
private ExecutorService executor; // TODO initialize the executor
private final int repeatFactor;

public AsyncMessageSenderImpl(int repeatFactor) {
this.repeatFactor = repeatFactor;
}

@Override
public void sendMessages(Message[] messages) {
for (Message msg : messages) {
// TODO repeat messages
executor.submit(() -> {
System.out.printf("(%s>%s): %s\n", msg.from, msg.to, msg.text); // do not change it
});
___

Create a free account to access the full topic