0

This is a question from a job interview:

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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You may check if current thread is instanceOf Reader or Writer

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.