[concurrency-interest] ThreadLocal.getIfPresent()

Nathan and Ila Reynolds nathanila at gmail.com
Wed Jun 6 14:40:49 EDT 2018


I think isPresent() should be added no matter what is decided about 
getIfPresent().  This will allow for "null" being present in ThreadLocal 
and detecting it.  For example, think of a situation where if the value 
is not present, you want to do some expensive operation.  At the end of 
the operation, you decide that nothing should be stored in ThreadLocal, 
but you want to cache this decision and prevent the expensive operation 
from being done again.  Without isPresent(), then some dummy Object has 
to be stored in ThreadLocal.  I have never run into this situation while 
using ThreadLocal, but it is a situation I bump into in other class designs.

As for getIfPresent(), I thought it was a good addition to the API.  I 
cannot think about a situation where I would have needed it.  If I did, 
I probably figured out some workaround.

-Nathan

On 6/6/2018 12:17 PM, Peter Levart via Concurrency-interest 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>  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>  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

-- 
-Nathan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20180606/0a7b6ee6/attachment.html>


More information about the Concurrency-interest mailing list