In this article we will look into Atomic Variables which can help us to write lock free and wait free algorithms which were not possible prior to Java 5.0.
Two main points about Atomic Variables are
1. Help to write lock free and wait free algorithm –
Under high contention ( lots of thread are fighting for lock ), JVM spends more time with scheduling of threads, managing contention, queues of waiting threads and less time in doing the real work.
This dramatically reduces the throughput of the process.
Problem with locking:
1) Thread in block state cannot do anything else.
2) If the blocked thread is high priority, then its a big disaster.
3) Can cause Dead lock
4) Managing a Block thread is a heavy weight process, so throughput decreases.
Soon we will see how can we write lock free algorithms using atomic variables
2. Implement very light weight process like CAS –
CAS (compares and swap):
Let’s take an example to understand the concept of CAS. Suppose we have once variable “i” and we are doing some calculation over “I” and storing the result back into “i”. In a nutshell-
i = someComplicateComputation( i )
for “i” = 1,
someComplicatedComputation(i) è 1234
In CAS Process following happens-
A memory location V will be defined.
A local variable A will be defined.
A local variable B will be defined.
V will hold the initial value of “i”. So
V = i =1
A = V = 1
B = result of that computation = 1234
compare ( V , A )
if
both values are same --> replace V with B's value.
else
this means in the mean while someone has changed the value of V, so repeat the whole process again. Lets someone changes the value of “i”, hence V to 2.
V = 2;
A = V = 2
B = result = 3246;
compare ( V , A )
and so on...!!
This is very light weight process. This CAS technique is implemented by atomic package classes.
Example – Lets write a simple program which first increase the number by 1, then decrease the number by 1, and then increase again by 1. So overall effect is increase the number by 1. Lets run 4 threads concurrently access the method and compare the performance of AtomicInteger Vs Integer.posted on 2012-08-06 10:50
ゞ沉默是金ゞ 阅读(940)
评论(0) 编辑 收藏 所属分类:
Java SE