How to make a method thread-safe in Java?
Is the following method thread-safe? How to make it thread-safe?
Each thread has its own stack (never share stack).
All local variables defined in a method will be allocated memory in stack.
When execution completed by a thread, stack frame will be removed.
Read full article from How to make a method thread-safe in Java?
Is the following method thread-safe? How to make it thread-safe?
class MyCounter { private static int counter = 0; public static int getCount() { return counter++; } } |
Make a method thread-safe - Method 1
Adding synchronized to this method will makes it thread-safe. When synchronized is added to a static method, the Class object is the object which is locked.
Is marking it synchronized enough? The answer is YES.
If the method is not static, then adding synchronized keyword willsynchronize the instance of the class, not the Class object.
public class MyCounter { private static AtomicInteger counter = new AtomicInteger(0); public static int getCount() { return counter.getAndIncrement(); } }Follow-up on thread stack
Each thread has its own stack (never share stack).
All local variables defined in a method will be allocated memory in stack.
When execution completed by a thread, stack frame will be removed.
Read full article from How to make a method thread-safe in Java?