5

I'm reading a code with this class:

public class MultiThreadedServer implements Runnable {
    // some more code
    protected Thread runningThread = null;

    public void run() {
        synchronized(this) {
            this.runningThread = Thread.currentThread();
        }
        // lots of code
    }
}

What is this supposed to mean ? The thread itself is used as flag to lock the ressource ? I don't get it at all.

Anyone knows ?

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
Csi
  • 526
  • 3
  • 22
  • `// blablahbla` - `// lots of blahblahblah` - this is a no-go to me. `this` points to the instance of `MultiThreadedServer `, not the Thread (which has an invalid identifier) – Binkan Salaryman May 29 '15 at 09:26
  • 3
    I love the space in `protected Thread running thread = null;` – Tschallacka May 29 '15 at 09:28
  • It doesn't use the thread as lock, it uses the Runnable object. Is the same object given to multiple threads? Are there other methods in the Runnable which synchronize? – Steven Pessall May 29 '15 at 09:28
  • Ah, typo, sorry guys. @Steven Pessall nothing else is synchronized in this method. – Csi May 29 '15 at 09:37

2 Answers2

3

this is a Runnable, not a thread, so the synchronization is not done on the thread itself as you write.

It might be somewhat confusing, but very workable if eg. the object is accessed by several concurrent threads.

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1

this.runningThread = Thread.currentThread(); Simply gives you a link to the current thread.

This way you don't have to call Thread.currentThread() all the time, saving you the method call overhead.

And uhm, the space in protected Thread running thread = null; doesn't help either...

Tschallacka
  • 27,901
  • 14
  • 88
  • 133