0

This is a question from a job interview:

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

GhostCat
  • 137,827
  • 25
  • 176
  • 248
prity
  • 1,519
  • 1
  • 12
  • 17

2 Answers2

2

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You may check if current thread is instanceOf Reader or Writer

Bhagya
  • 63
  • 5
  • `Thread.currentThread()` will always return something that is `instanceof Thread`. But `extends Thread` usually is a code smell, so merely looking at the _type_ of the current Thread object won't tell you anything if your code doesn't stink. Like GhostCat said, it's better to use the _identity_ of the object. Best of all though would be to not write code that does different things depending on who's calling it. – Solomon Slow Apr 07 '17 at 14:55