java - Using atomic for generating unique id -
class abc{ private static random random = new random(); private static atomiclong uniquelongid = new atomiclong(system.currenttimemillis()); public static long getuniquelongid(){ long id = uniquelongid.incrementandget(); long uniqueid = math.abs(random.nextlong()) + id; homecoming uniqueid; //the above code can write in 1 line //return math.abs(random.nextlong())+uniquelongid.incrementandget(); } }
will above method getuniquelongid() give me unique id in multithreaded environment. concern here is: knowing uniquelongid atomic , assuming calling incrementandget() thread-safe call, other part of code not synchronized. not mean method getuniquelongid() not thread safe? , may not neccesarily homecoming unique id?
please explain..
the java 7 docs write:
instances of java.util.random
threadsafe. however, concurrent utilize of same java.util.random
instance across threads may encounter contention , consequent poor performance. consider instead using threadlocalrandom
in multithreaded designs.
so code thread safe in java 7. every operation either phone call thread-safe method, or operating on local variables only. , don't require atomicity, i.e. don't require next sequence number paired next random number.
as (per comment) there no such guarantees in older versions of api documentation, implementations in theory non-threadsafe. however, looking @ src.zip
in sun jdk 1.4.2.19 (which oldest version have around), code uses atomic variable, providing thread-safe behaviour in practice.
that said, code has number of other problems. quoted above, performance might bad. assylias wrote in comment, approach won't give more unique numbers simple random
would. furthermore, math.abs(long.min_value)
still negative, , positive random number plus id might cause overflow , wrap-around. if need positive numbers, you'll have add together more care. final uniqueid &= 0x7fffffffffffffffl
might more suitable math.abs
along way.
java atomic uniqueidentifier java.util.concurrent
No comments:
Post a Comment