How can I make sure a method is only called once by multiple threads?

后端 未结 5 1593
孤城傲影
孤城傲影 2020-12-17 17:46

I have the following structure:

public void someMethod(){  
   //DO SOME STUFF
   try{  
    doSomeProcessing();  
   }  
   catch (Exception e){  
                


        
5条回答
  •  盖世英雄少女心
    2020-12-17 18:19

    We wrote a library that includes a utility lazily load/call a method. It guarantees single usage semantics and preserves any thrown exceptions as you'd expect.

    Usage is simple:

    LazyReference heavyThing = new LazyReference() {
      protected Thing create() {
        return loadSomeHeavyData();
      }
    };
    
    public void someMethod(){  
      //DO SOME STUFF
      try{  
        doSomeProcessing();  
      }  
      catch (Exception e){  
        heavyThing.get();  
        doSomeProcessing();      
      }    
    }  
    

    All threads block on the get() and wait for the producer thread (the first caller) to complete.

提交回复
热议问题