prity
prity

Reputation: 1519

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?

Upvotes: 0

Views: 896

Answers (2)

GhostCat
GhostCat

Reputation: 140633

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.

Upvotes: 2

Bhagya
Bhagya

Reputation: 63

You may check if current thread is instanceOf Reader or Writer

Upvotes: 0

Related Questions