[concurrency-interest] synchronization based on a key

√iktor Ҡlang viktor.klang at gmail.com
Thu May 24 11:56:22 EDT 2012


On Thu, May 24, 2012 at 5:46 PM, R.A. Porter <coyotesqrl at gmail.com> wrote:

> How about a simpler approach:
>
> void foo(String key) {
>   synchronized(key.intern()) {
>     // process this key
>   }
> }
>

Wow, I'd never do that.
How about just having a map from String to Semaphore?

Cheers,
√


>
>
> -r
>
>
> On Thu, May 24, 2012 at 7:22 AM, bhm <bheem at sbcglobal.net> wrote:
>
>> I have a method that needs to be synchronized based on a key passed as
>> parameter, that is, for same key multiple threads shouldn't be
>> running. Following is what I did--
>>
>>
>> static final ConcurrentMap<String,Boolean> IN_PROGRESS =
>>   new ConcurrentHashMap<String,Boolean>();
>>
>> void foo(String key){
>>    if(null == IN_PROGRESS.putIfAbsent(key, Boolean.TRUE)){
>>      // no other thread is processing this key
>>      try{
>>          // process this key
>>      } finally {
>>         // done with processing this key
>>         IN_PROGRESS.remove(key)
>>      }
>>    } else {
>>      // some other thread is running this key, discard it
>>    }
>> }
>>
>> this works if I need to discard the request to process the key from
>> thread t1 when another thread, t2, is processing that key.
>>
>> I need help to do following-
>> make thread t1 wait while t2 is processing the key and resume t1 when
>> t2 is finish processing same key.
>>
>> I'm aware that if there are multiple threads t1,t3,t4.. etc waiting
>> for t2 to finish anyone of these thread can wake up and start
>> processing the key irrespective of their order (if there is any) of
>> asking to process the key.
>>
>> Thanks for help.
>>
>> Bheem
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>>
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>


-- 
Viktor Klang

Akka Tech Lead
Typesafe <http://www.typesafe.com/> - The software stack for applications
that scale

Twitter: @viktorklang
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120524/e8c30e6a/attachment.html>


More information about the Concurrency-interest mailing list