I\'m looking for a way to synchronize a method based on the parameter it receives, something like this:
public synchronized void doSomething(name){
//some co
I have a much simpler, scalable implementation akin to @timmons post taking advantage of guavas LoadingCache with weakValues. You will want to read the help files on "equality" to understand the suggestion I have made.
Define the following weakValued cache.
private final LoadingCache syncStrings = CacheBuilder.newBuilder().weakValues().build(new CacheLoader() {
public String load(String x) throws ExecutionException {
return new String(x);
}
});
public void doSomething(String x) {
x = syncStrings.get(x);
synchronized(x) {
..... // whatever it is you want to do
}
}
Now! As a result of the JVM, we do not have to worry that the cache is growing too large, it only holds the cached strings as long as necessary and the garbage manager/guava does the heavy lifting.