Search code examples
javamultithreadingsynchronizedsynchronized-block

Java multithreading - reader and writer thread in synchronized block


This is a question from a job interview:

How to identify read thread and write thread in a synchronized block?


Solution

  • You can always do something like:

    Thread current = Thread.currentThread()
    

    And now; when you have a map/list/... of threads, you can simply compare references. Simple example:

    You add two fields to your class:

    private Thread reader = 
    private Thread writer = 
    

    And then you could do

    synchronized foo() {
      if (Thread.currentThread() == reader) ...
    

    And for the record: although things look that easy, a person dealing with "this problem" should rather step back: this smells XY problem all over the place.

    Meaning: in the "real" world; I would consider code like this to be bad practice. Most likely, it tries to solve a problem that should be solved in other ways!

    So, the answer to an interviewer would better be a combination of the direct technical answer; but pointing out that "bad practice" issue.