rest() を同期し、さらにメソッドを追加しないわけではありません。より多くのメソッドが必要になる場合があります。例えば
NamedCounter counter = new NamedCounter();
counter.increment();
// at this exact time (before reaching the below line) another thread might change changed the value of counter!!!!
if(counter.getCount() == 1) {
//do something....this is not thread safe since you depeneded on a value that might have been changed by another thread
}
上記を修正するには、次のようなものが必要です
NamedCounter counter = new NamedCounter();
if(counter.incrementAndGet()== 1) { //incrementAndGet() must be a synchronized method
//do something....now it is thread safe
}
代わりに、すべてのケースをカバーする Java の組み込みクラス AtomicInteger を使用してください。または、スレッドセーフを学習しようとしている場合は、AtomicInteger を標準として (学習するために) 使用してください。
プロダクション コードの場合は、よく考えずに AtomicInteger を使用してください。AtomicInteger を使用しても、コードのスレッド セーフが自動的に保証されるわけではないことに注意してください。API によって提供されるメソッドを使用する必要があります。彼らは理由があってそこにいます。