Hello. I can not explain for myself the principle of the organization and work of threads in Java. I will try to briefly explain the essence of the problem. There is a class MyClass :

 public MyClass { public void method1(int n) { int c = method2(n); // Ещё что-то } public int method2(int n) { // что-то делает } } 

I create a single instance of this class called myObject . I create Runnable , into which I pass a link to my object and in run () I perform the following actions:

 public void run() { while (true) { myobject .method2(someInt); } } 

Then I run several threads with this Runnable . Please note that the methods are not synchronized, nothing is synchronized at all. The first thread enters method1 and calculates C = C1, then it is pushed out, after that the second stream enters method1, counts C = C2 and is superseded. After that, the first thread wakes up and continues with the execution of method 1, what will be the value of C for the continuing flow # 1?

    1 answer 1

    C1. After all, C is a local variable.

    PS: of course, if method2 has no side effect, otherwise the process of calculating c itself will be subjected to a race. And by the way, this question is not about the organization of threads in Java, but generally multithreading.

    • Ok, this question was like a simplified version of the following. Is it advisable to use the same http client instance to send requests from different streams, while not sending the requester itself? - Vladimir
    • It depends on what kind of HTTP client you use. But in general, no, it is not advisable. The Apache HTTP client has some components that can be fumbled between different requests and different threads. - cy6erGn0m
    • Thanks for the answer. I use netty. I ran through it with debugging, like local variables are used everywhere, I don’t intend to do that, it’s just that the opinion of the more experienced people became interested. If for the sending itself only local variables are used, i.e. the socket is saved to lok. variable, etc. then it is purely theoretical that should work? - Vladimir
    • Theoretically yes. But in practice, you should not do this if the documentation does not explicitly state that they guarantee security. Otherwise, they can change their mind at any time and your application will fall apart. - cy6erGn0m
    • Thank you very much for the clarification - Vladimir