0

I have dynamic array of hashtables

Can I use synchronized for each of them separately? Like synchronized(array[1]) { code .. }, synchronized(array[2]) { code .. }

Thanks

1
  • What are you trying to achieve? This question doesn't make sense without a bit of context. Commented Jan 23, 2010 at 20:18

2 Answers 2

3

You can certainly synchronize on the object in a particular position in the array writing:

synchronized (arr[x]) {
  ...
}

However, just be careful to make sure you understand whether this is doing what you want it to do.

This will lock on the particular object referenced by arr[x]. However, it won't buy you any thread-safety in terms of accesses to the array itself-- in other words, for example:

  • while you're locking on the object at arr[x], another thread could still potentially change which object is at arr[x];
  • if two threads simultaneously access the same position of arr (either to read which hash map/object is there, or to set a new one), there'll be a race condition.

I also tend to agree with akappa -- what you're doing sounds slightly unusual, and it might be better to rephrase your question as "what data structure do I need in order to do X" rather than assuming that an array of hashmaps is the appropriate one from the outset?

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

Comments

2

Sure, but it's better to use a concurrent map os a concurrent skip list for throughput concerns, if you can.

BTW, if you provide us a bit of context, we can suggest you a (maybe) better data organization and structure.

1 Comment

Yea, I would argue there is absolutely no reason to use a hastable ever.

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.