Java Thread-safe

http://javarevisited.blogspot.ca/2012/01/how-to-write-thread-safe-code-in-java.html

http://jcip.net.s3-website-us-east-1.amazonaws.com/listings.html

How to write Thread-Safe Code in Java

thread-safety or  thread-safe code in Java 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 concurrent environment is not thread-safe. thread-safety is one of the risk introduced by using  threads in Java and I have seen java programmers and developers struggling to  write thread-safe code or just understanding  what is thread-safe code and what is not? This will not be very detailed article on thread-safety or low level details of  synchronization in Java instead we will keep it simple and  focus on one example of non thread-safe code and try to understand what is thread-safety and  how to make an code thread-safe.

How to make Thread-Safe Code in Java

Example of Non Thread Safe Code in Java

how to write thread-safe code in java example Here is an example of  non thread-safe code, look at the code and find out  why this code is not thread safe ?

/*
  * Non Thread-Safe Class in Java
 */
public class  Counter {
  
    private int count;
  
    /*
     * This method is not thread-safe because ++ is not an atomic operation
     */
    public int getCount(){
        return count++;
    }
}

Above example is not thread-safe because ++ (increment operator) is not an  atomic operation and can be broken down into read, update and write operation. if multiple thread call getCount() approximately same time each of these three operation may coincide or overlap with each other for example while thread 1 is updating value , thread 2 reads and still gets old value, which eventually let thread 2 override thread 1 increment and  one count is lost because multiple thread called it concurrently.

How to make code Thread-Safe in Java


There are multiple ways to make this code thread safe in Java:

1) Use  synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes possibility of coinciding or interleaving.

2) use  Atomic Integer, which makes this ++ operation atomic and since  atomic operations are thread-safe and saves cost of external synchronization.


here is a thread-safe version of Counter class in Java:



/*
 *  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();
    }
}


Important points about Thread-Safety in Java

Here is some points worth remembering to  write thread safe code in Java, these knowledge also helps you to avoid some serious concurrency issues in Java like race condition or  deadlock in Java:

1) Immutable objects are by default thread-safe because there state can not be modified once created. Since String is immutable in Java, its 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.
4)  Static variables if not synchronized properly becomes major cause of thread-safety issues.

5) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.
6) Atomic operations in Java are thread-safe e.g. reading a 32 bit int from memory because its an atomic operation it can't interleave with other thread.
7) local variables are also thread-safe because each thread has there own copy and using local variables is good way to writing thread-safe code in Java.
8) In order to avoid thread-safety issue minimize sharing of objects between multiple thread.
9)  Volatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct JVM not to reorder or optimize code from threading perspective.



That’s all on  how to write thread safe class or code in Java and avoid serious concurrency issues in Java. To be frank thread-safety is a little tricky concept to grasp, you need to think concurrently in order to catch whether a code is thread-safe or not. Also  JVM plays a spoiler since it can  reorder code for optimization, so the code which looks sequential and runs fine in development environment not guaranteed to run similarly in production environment because JVM may ergonomically adjust itself as server JVM and perform more optimization and reorder which cause  thread-safety issues.

Thanks


Read more:  http://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.html#ixzz2Q6tfnmYO

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值