Reputation: 62804
If two threads in a process generate a new GUID concurrently using .NET API (Guid.NewGuid()
) is it possible that the two GUIDs will be identical?
Thanks.
UPDATE I want to get practical. I know that it is widely assumed that GUIDs are unique for all practical purposes. I am wondering if I can treat GUIDS produced by the different threads of the same process in the same manner.
Upvotes: 27
Views: 9532
Reputation: 239714
Well, current implementations of .Net use CoCreateGuid internally:
To a very high degree of certainty, this function returns a unique value – no other invocation, on the same or any other system (networked or not), should return the same value.
Upvotes: 1
Reputation: 128317
Possible (as in, could it ever happen, in the lifetime of the universe)? Yes.
Likely (at all)? No.
Microsoft utilizes a Version 4 algorithm for generating GUIDs (see also: here), which produces a completely (pseudo-)random number.
Given the number of possible GUIDs, the probability of a duplicate is tiny. Like, unfathomably tiny.
You are concerned with concurrency: fortunately, the NewGuid
method is thread-safe, which means it either locks or utilizes a thread-static random number generator for its purposes. The first approach would effectively serialize all calls to NewGuid
so that they occur in sequence (never simultaneously) while the latter would make calls from separate threads independent of one another.
In either case, the only reason you would have to fear getting duplicates from two threads creating random numbers simultaneously -- GUID
or not -- would be if the underlying generators used by the threads were operating (1) from the same seed (which could only result from a design flaw), and (2) in a time-dependent manner (which the version 4 GUID algorithm does not).
So yes, practically speaking, you can treat GUIDs generated concurrently from separate threads to be unique.
Upvotes: 35
Reputation: 8166
It's not likely to happen...
http://msdn.microsoft.com/en-gb/library/system.guid(v=VS.95).aspx
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.[...]
A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.
Upvotes: 1
Reputation: 20157
Not possible. Static methods of Guid
are guaranteed to be thread-safe. See documentation here.
Upvotes: 8