A
A
Arti-Jack2017-02-10 10:52:18
Java
Arti-Jack, 2017-02-10 10:52:18

Why doesn't the system accept a response without calling this?

Good day.
I took the test yesterday and finally passed it. But there are some questions about this.
Here is the text of the assignment:

In the monitoring system, tracking of each device is implemented in a separate thread.
Each thread must constantly send messages to the server by calling sender.send(message) (sender is a shared object accessible from each TestThread instance)

class TestThread extends Thread {
   /*.....*/
   String message;
   public void run() {
     while (true){
         /*YOUR CODE will be placed HERE*/ 
       }
     }
}

Sending a message is a lengthy process.
It is important that devices send messages in turn, that is, only one thread sends a message at a time.
Add the necessary lines to the code so that all devices transmit the message in the required way.
There is no need to delay the execution of threads.

Naturally, I guessed that thread synchronization was needed here. Moreover, on a single monitor, which here is sender .
That is, my answer was:
synchronized (sender) {
    sender.send(message);
}

But the system stubbornly refused to accept this kind of response.
In the end it turned out that the answer here is:
synchronized (sender) {
    sender.send(this.message); 
}

If I understand correctly, then there should be no difference between this.messageand message.
After all, when we call the method run(), we implicitly pass a reference to the calling instance there. And Java automatically replaces such variable calls with this.
Is it the wrong logic of my reasoning, or did the developers of the test do something wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Alexandrov, 2017-02-10
@jamakasi666

I can assume that in the case of threads, the this.message variable means that the thread will work with the data that was at the time of its launch / creation, and not those that actually lie in memory at the moment. If without this, then the data will be taken exactly those that are actually in the variable at the moment, but the thread could sleep and the data should have been sent by others.
This is just a guess, and most likely wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question