Java synchronizing based on a parameter (named mutex/lock)

后端 未结 8 1785
逝去的感伤
逝去的感伤 2020-12-05 02:50

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         


        
8条回答
  •  Happy的楠姐
    2020-12-05 03:05

    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.

提交回复
热议问题