This is a question from a job interview:
How to identify read thread and write thread in a synchronized block?
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.
You may check if current thread is instanceOf Reader or Writer
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.