+ 1
What is thread safety?
Hey Can anyone tell me what is thread safety? I can't understand it Thanks to all
2 Antworten
+ 3
thread-safety refers to code which can safely be used or shared in concurrent or multi-threading environment and they will behave as expected. any code, class, or object which can behave differently from its contract on the concurrent environment is not thread-safe.
check these two examples below :
/*
* Thread-Safe Example in Java
*/
public class Counter {
private int count;
AtomicInteger atomicCount = new AtomicInteger( 0 )
/*
* This method thread-safe now because of locking and synchornization
*/
public synchronized int getCount(){
return count++;
}
/*
* This method is thread-safe because count is incremented atomically
*/
public int getCountAtomically(){
return atomicCount.incrementAndGet();
}
}
check non safe:
/*
* Non Thread-Safe Class in Java
*/
public class Counter {
private int counts
/*
* This method is not thread-safe because ++ is not an atomic operation
+ 1
Thank you a lot