-
Notifications
You must be signed in to change notification settings - Fork 851
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Auto-detect Android and use an Android-friendly IdGenerator instance. (…
…#3176) * Auto-detect Android and use an Android-friendly IdGenerator instance. * simplify the random initialization * Make the AndroidFriendlyRandomIdGenerator even simpler by just keeping a single Random instance
- Loading branch information
Showing
3 changed files
with
64 additions
and
4 deletions.
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AndroidFriendlyRandomIdGenerator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* | ||
* Copyright The OpenTelemetry Authors | ||
* SPDX-License-Identifier: Apache-2.0 | ||
*/ | ||
|
||
package io.opentelemetry.sdk.trace; | ||
|
||
import io.opentelemetry.api.trace.SpanId; | ||
import io.opentelemetry.api.trace.TraceId; | ||
import java.util.Random; | ||
|
||
/** | ||
* {@link IdGenerator} instance that doesn't use {@link java.util.concurrent.ThreadLocalRandom}, | ||
* which is broken on most versions of Android (it uses the same seed everytime it starts up). | ||
*/ | ||
enum AndroidFriendlyRandomIdGenerator implements IdGenerator { | ||
INSTANCE; | ||
|
||
private static final Random random = new Random(); | ||
|
||
private static final long INVALID_ID = 0; | ||
|
||
@Override | ||
public String generateSpanId() { | ||
long id; | ||
do { | ||
id = random.nextLong(); | ||
} while (id == INVALID_ID); | ||
return SpanId.fromLong(id); | ||
} | ||
|
||
@Override | ||
public String generateTraceId() { | ||
long idHi; | ||
long idLo; | ||
do { | ||
idHi = random.nextLong(); | ||
idLo = random.nextLong(); | ||
} while (idHi == INVALID_ID && idLo == INVALID_ID); | ||
return TraceId.fromLongs(idHi, idLo); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters