如何使Java Spring Component类线程安全?

I have a spring class that when you call httpDatastoreFacade.getDatastore() it should give you the REST request thread safe datastore:

@Component
public class HttpDatastoreFacade {
  private Boolean useAttribute = Boolean.FALSE;

  public String getDatastore() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextholder.currentRequestAttributes()).getRequest();
    String datastore = request.getParameter("datastore");

    if(useAttribute) {
      datastore = String.valueOf(request.getAttribute("datastore"));
    }

    return datastore;
  }

  public void setDatastore(String datastore, Boolean useAttribute) {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextholder.currentRequestAttributes()).getRequest();
    request.setAttribute("datastore", datastore);
    this.useAttribute = useAttribute;
  }

  public Boolean getUseAttribute() {
    return useAttribute;
  }
}

Sometimes in my code I need to change that datastore but then I want to immediately change it back after I call whatever code needs the datastore differently:

 @Component
  public class someClass() {
    @Autowired
    private HttpDatastoreFacade datastoreFacade;

   @Autowired
   private OtherClass otherClass;

   public void someMethod() {
     String savedDatastore = datastoreFacade.getDatastore();
     String savedUseAttribute = datastoreFacade.getUseAttribute;

     //setDatastore to new settings 
     datastoreFacade.setDatastore("newStore", true);

     //this is where I call my method's or methods that need this new datastore
     otherClass.callSomeMethod();

     //set the datastore back to old value
     datastoreFacade.setDatastore(savedDatastore , savedUseAttribute );
   }
 }

My issue is that I'm running into threading problems where useAttribute is true but the datastore isn't set in the request attribute.

I'm looking for a better java pattern where I can lock the HttpDatastoreFacade while I do my otherClass.callSomeMethod() or whatever other calls I need to make until I set the HttpDatastoreFacade back to normal. otherCalss.callSomeMethod may be calling other methods that use HttpDatastoreFacade as well and they may want to set it how they need it. So maybe I need some short of datastore stack that is thread safe?

评论