I have a static method with the following signature:
public static List<ResultObjects> processRequest(RequestObject req){ // process the request object and return the results. }
What happens when there are multiple calls made to the above method concurrently? Will the requests be handled concurrently or one after the other?
accessing the code is no problem, static methods can be called with multiple threads. It depends on how it is programmed in the method, if the code is not thread safe, it will cause problems.
Methods declared as static have several restrictions: They can only directly call other static methods. They can only directly access static data. They cannot refer to this or super in any way.
Static methods can be accessed without having to create a new object. A static method can only use and call other static methods or static data members. It is usually used to operate on input arguments (which can always accept), perform calculation and return value.
@SangitGurung it's not. The methods are executed in separate activation frames.
The .NET class library provides a number of classes for synchronizing threads. See Overview of Synchronization Primitives. You can use the Monitor class or a compiler keyword to synchronize blocks of code, instance methods, and static methods. There is no support for synchronized static fields.
Multiple threads are allowed to access the methods and fields, but only a single thread is allowed at any one time. Learn about .NET thread synchronization primitives used to synchronize access to a shared resource or control thread interaction See how unhandled exceptions are handled in .NET.
In .NET Framework and Xamarin applications only, you can use the SynchronizationAttribute on any ContextBoundObject to synchronize all instance methods and fields. All objects in the same context domain share the same lock. Multiple threads are allowed to access the methods and fields, but only a single thread is allowed at any one time.
Synchronizing data for multithreading. When multiple threads can make calls to the properties and methods of a single object, it is critical that those calls be synchronized. Otherwise one thread might interrupt what another thread is doing, and the object could be left in an invalid state.
Answering exactly your question:
You need to add the synchronized
modifier if you are working with objects that require concurrent access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With