0

I need to synchronize this method on id argument value. I was thinking about using string pool reference, is there a better way?

static void f(Number id) {
  String s = String.valueOf(id).intern();
  synchronized (s) {
   // syncronize this block by id value
  }
}
Ahmad Shahwan
  • 1,662
  • 18
  • 29
Seby
  • 262
  • 3
  • 15
  • Don't do *that*. If you have Guava, you can use [StripedLock](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/util/concurrent/Striped.html) for a nicer way to handle this. – Kayaman May 28 '18 at 08:43
  • Guava StripedLock or Interner? – Seby May 28 '18 at 09:01
  • It's not a good idea to a) involve the String pool in things it wasn't meant for b) create your own "clever" synchronization "solutions". See also in the linked question the statement: `As others have pointed out, using intern() for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea`. – Kayaman May 28 '18 at 09:05
  • static final Striped locks = Striped.lazyWeakLock(10); locks.get(id).lock(); ? – Seby May 28 '18 at 09:13
  • Do you really need lazy and weak locks? – Kayaman May 28 '18 at 09:14
  • We have thousands of ids, concurrent operations may be 10/20, i was thinking that a weak lock was better? am i wrong? – Seby May 28 '18 at 09:20
  • https://stackoverflow.com/questions/11124539/how-to-acquire-a-lock-by-a-key/11125602#11125602 – Seby May 28 '18 at 09:34
  • Why do you think weak lock is better? – Kayaman May 28 '18 at 09:34

1 Answers1

0

StripedLock seems to be a good solution, better than guava's interner.

How to acquire a lock by a key

Seby
  • 262
  • 3
  • 15