Interview questions:
is the following method thread-safe? How do you make it a thread-safe method?
class MyCounter { privatestaticint counter = 0; Public Static int GetCount () { return counter++; }}
This article will explain a common face question that has been asked by Google and many other companies. It involves relatively elementary, rather than how to design complex concurrent programs.
First, the answer to this question is no, because the counter++ operation is not an atomic operation, but consists of multiple atomic operations.
For example, when a thread is accessing the data, another thread is performing an incremental operation;
When thread 1 accesses the method at T1 time, thread 2 of threads may not have done this method. Therefore, the value of thread 1 that returns threads may not have been incremented.
Make the GetCount method thread safe-way One
Use the keyword synchronized to decorate the GetCount method to make it thread safe. When you use synchronized to modify a static method, the class object becomes a lock.
Is it enough to use synchronized, the answer is yes.
class MyCounter { privatestaticint counter = 0; Public Static synchronized int GetCount () { return counter++; }}
If the method is not a static method, then using the keyword synchronized will synchronize the instance object instead of the class object.
Make the GetCount method thread safe-way Two
In this particular count example, by using the Atomicinteger Atom class under the Java.util.concurrent.atomic package, you can turn the count++ operation into an atomic operation, as follows.
Import Java.util.concurrent.atomic.AtomicInteger; Public class MyCounter { privatestaticnew atomicinteger (0); Public Static int GetCount () { return counter.getandincrement (); }}
Some other useful facts about thread safety
Local variables are thread-safe in Java.
Each thread will have its own stack, and two different threads will not share the same stack.
Local variables within all methods will allocate space in the stack, and the stack frame will be removed as soon as the method of the front-end thread is executed.
Link: http://www.programcreek.com/2014/02/how-to-make-a-method-thread-safe-in-java/
How to create thread-safe methods in "simple Java" Java