Say I have an array of thousands of objects, and a small number of threads that might access each of the objects. I want to protect the access to one of the objects methods. Easiest way would be to declare that method as synchronized
. However, that might result in creating thousands of monitors, whichever way they are implemented. If this were Win32, I'd never create thousands of kernel objects such as Mutex, but CRITICAL_SECTIONs might be plausible. I'm wondering what's the case in Java. Given the chance of contention is low, would the use of monitors impose more than the sheer amount of memory they require? How common a practice is it to use such low granularity synchronization in Java?
(There are obviously workarounds such as using a much smaller array of synchronization objects, which will be accessed using some hash. I'm not looking for a practical solution, I'm looking for an insight).