简体   繁体   中英

how the same Instance work on different method on another class in java

Same instance is used in multiple method based on the argument providing. can we consider thread safety here. Let's assume that we've 2 class, Class Main & Class demo .

Class Demo {
   returnType methodExample(args...) {
      //based on the argument provide it returns
      return something
   }
}

Class Main {
   Demo demo = new Demo();

   returnType method1() {
      value = demo.methodExample(args);
   }
   
   returnType method2() {
      value = demo.methodExample(args);
   }
}

will it share same Demo Instance. And what of both method works asynchronously. please also describe the case in Spring Injecting by @AutoWired annotation

Apologies for typos or other mistakes.

yes it will share same Demo instance. but the calculations are performed under method methodExample() is based on what value you are passed on parameters. for using @autowire first you have to use @component annotation on Demo Class.

@Component
Class Demo {
   returnType methodExample(args...) {
      //based on the argument provide it returns
        return something
   }
}
Class Main {
   @Autowired
   Demo demo;

   returnType method1() {
      value = demo.methodExample(args);
   }

   returnType method2() {
      value = demo.methodExample(args);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM