[concurrency-interest] ThreadLocal.getIfPresent()

Henri Tremblay henri.tremblay at gmail.com
Wed Jun 6 14:33:29 EDT 2018


Hi,

Jumping into the conversation. isPresent would be useful and probably
enough (better?).

Right now, if you want to mimic the ThreadLocalRandom (and the
ConcurrentHashMap), you need to have access to the probe.

static final int getProbe() {
    return UNSAFE.getInt(Thread.currentThread(), PROBE);
}

And it happened to me a bunch of time to need to know if there's something
in a ThreadLocal without kicking its initialization. So isPresent would
nice. Both can be useful, but isPresent is a must have. If can help
mimicking code like this:

if ((h = ThreadLocalRandom.getProbe()) == 0) {
    ThreadLocalRandom.localInit();      // force initialization
    h = ThreadLocalRandom.getProbe();
    wasUncontended = true;
}


Then... having access to the Probe would be nice too...

Henri

On 6 June 2018 at 14:17, Peter Levart via Concurrency-interest <
concurrency-interest at cs.oswego.edu> wrote:

>
>
> On 06/06/18 19:28, David Lloyd wrote:
>
> On Wed, Jun 6, 2018 at 12:09 PM, Peter Levart <peter.levart at gmail.com> <peter.levart at gmail.com> wrote:
>
> Di David,
>
> On 06/06/18 18:48, David Lloyd wrote:
>
> On Wed, Jun 6, 2018 at 10:17 AM, Peter Levart via Concurrency-interest<concurrency-interest at cs.oswego.edu> <concurrency-interest at cs.oswego.edu> wrote:
>
> Are you thinking about possible "inconsistency" between overridden get() and
> not overridden getIfPresent() ? Like for example:
>
> Exactly.  You could possibly get around the issue by declaring it like this:
>
> public class ThreadLocal<T> {
>     // ...
>     public static <T> T getIfPresent(ThreadLocal<T> tl) {
>         return Thread.currentThread().hasThreadLocalInternal(tl) ?
> tl.get() : null;
>     }
>     // ...
> }
>
>
>
> Or there could simply be the following method in ThreadLocal:
>
> /**
>  * @return true if current thread has a value present for this
> thread-local variable; false if not.
>  */
> public boolean isPresent()
>
>
> Would that be preferable?
>
> Peter
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20180606/730fc969/attachment.html>


More information about the Concurrency-interest mailing list