This is the my code..
@immutable // This is not a standard annotation .Only for Showing that behavior of Class
class OneValueCached{
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
public OneValueCached(BigInteger i,BigInteger[] factors){
lastNumber=i;
lastFactors=Arrays.copyOf(factors, factors.length);
}
public BigInteger[] getFactors(BigInteger i){
if(lastNumber==null || !lastNumber.equals(i))
return null;
else
return Arrays.copyOf(lastFactors, lastFactors.length);
}
}
@threadSafe // This is not a standard annotation .Only for Showing that behavior of Class
public class VolatileCachedFactorizer implements Servlet{
private volatile OneValueCached cache=new OneValueCached(null, null);
public void service(ServletRequest req, ServletResponce resp){
BigInteger i= extractFromRequest(req);
BigInteger[] factors=cache.getFactors(i);
if(factors==null){ // ---> line 1
factors=factor(i); // --> line 2
cache=new OneValueCached(i, factors);
}
encodeIntoResponse(resp,factors);
}
}
Why class VolatileCachedFactorizer is thread according to Book But My point is..
1. @ Line 1 if 2 thread coming at same time at that point 1st thread
check condition and found factor=null and 2nd thread
also check same condition at the same time after 1st thread
suspend at line 2nd and found factor=null
And both will be create new OneValueCached
Object Then how this code is thread safe.. According to book this is thread safe..
Thank's
When sharing is important, provide explicit synchronization to make certain that the program behaves in a deterministic manner. A procedure is thread safe when it is logically correct when executed simultaneously by several threads.
1) Immutable objects are by default thread-safe because their state can not be modified once created. Since String is immutable in Java, it's inherently thread-safe. 2) Read-only or final variables in Java are also thread-safe in Java. 3) Locking is one way of achieving thread-safety in Java.
In computer programming, thread-safe describes a program portion or routine that can be called from multiple programming threads without unwanted interaction between the threads. (A thread is an instance of the program running on behalf of some user or process.)
It's thread safe because there is never inconsistency between lastNumber
and lastFactors
which could result in incorrect factoring. It makes no guarantees that the minimum amount of factoring will take place: the OneValueCached
can be created more than once, but that's still thread-safe.
The exact notion of "thread-safety" has not been defined here. What do you expect to happen/not happen for this code to be thread-safe?
Cache
object when service
is called concurrently, then it's not thread-safe.Again, without the definition of thread-safe behavior for this situation we cannot really tell for sure.
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