Valentin Kovalenko | 22 May 2013 12:08
Picon

a mistake in JDK-example OR invocation of the method Thread.interrupt() actually must be externally synchronized?

Hi,
as far as I know there is no need to externally synchronize invocation of the method Thread.interrupt(). So I suppose the following code in T2 correctly performs interrupt of T1:

//T2 run()
t1.interrupt();

//T1.run()
synchronized(this) {// this == t1
try {
while(true) {
wait();
}
} catch (InterruptedException e) {
}
}

However I've found the following document in the JDK7 documentation: Java Thread Primitive Deprecation http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html (note that the document exists at least since JDK1.4 http://docs.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html).
This document confused me. If you'll look at the "Can I combine the two techniques to produce a thread that may be safely "stopped" or "suspended"?" paragraph, you can see a similar example (for the sake of brevity I didn't copy-paste the example) and a strange comment for that example. The comment states the following:
"If the stop method calls Thread.interrupt, as described above, it needn't call notify as well, but it still must be synchronized. This ensures that the target thread won't miss an interrupt due to a race condition."
It seems like a mistake for me, that is I think that the comment should be like following:
If the stop method calls Thread.interrupt, as described above, it needn't call notify as well, AND it NEED NOT be synchronized.

Could someone please confirm that the specified statement is a mistake, or may be I misunderstand the comment or the proper way to invoke Thread.interrupt() method?

-- 
Homo homini lupus est.
_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Andy Nuss | 22 May 2013 06:24
Picon
Favicon

can a core see semi-constructed objects in array before the publishing act

Hi,

I have a volatile array "ar" of objects.  I wish to add tuples of N objects to the array with the following idiom:

void publish (Object obj1, Object obj2, Object obj3, Object obj4)
{
     lock();                                      // atomic lock
     Object[] ar = this.ar;
     int pos = calculatepos(...);
     ar[pos+1] = obj2;
     ar[pos+2] = obj3;
     ar[pos+3] = obj4;
     ar[pos] = obj1;                         // if the reader sees null, the tuple is empty to him at that moment
     this.ar = this.ar;                       // java.util.concurrency uses this idiom to publish
     unlock();
}

The readers do not lock().  Instead, they just get a reference to the volatile "ar", and iterate thru the array looking at the first element of the tuple.  If the element is not null, then the readers assume that (1) the other elements of the tuple are not null, and (2) that the various obj1 ... obj4 elements, which are effectively final, if the references are non null, then their values have been fully constructed.

I'm worried about assumption (1) because may the four ar[pos+n] = objN; assignments might be reordered.

I'm worried about assumption (2) because the publishing act for the effectively final objects is this.ar = this.ar, but maybe other cores could see the reference ar[pos] before the tuple's object's member variables are published via this.ar = this.ar.

Obviously, is the 4 objects are immutable with final fields, this is not a problem, but I expect them to be effectively final.

Any ideas?  If my assumptions are wrong, then one idea is to use another volatile int[] indexar with -1 values for invalid.  Then the function becomes something like:

void publish (...)
{
     lock();
     Object[] ar = this.ar;
     int len = lengthofobjarray();
     int pos = calculatepos(...);
     ar[len] = obj1;
     ar[len+1] = obj2;
     ar[len+2] = obj3;
     ar[len+3] = obj4;
     setlengthofobjarray(len+4);
     this.ar = this.ar;
     indexar[pos/4] = len;
     this.indexar = this.indexar;
     unlock();
}

Where there is no replace in the Object[] ar, only growth or reallocation, and given that the indexar has only one integer index to set per tuple, after the tuple has been published, then I think we're safe.

Andy
_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Stas Oskin | 19 May 2013 10:13
Picon
Gravatar

Invitation to connect on LinkedIn

 
 
 
 
 
From Stas Oskin
 
CTO at eyecam
Israel
 
 
 
 
 
 
 

I'd like to add you to my professional network on LinkedIn.

- Stas

 
 
 
 
 
 
 
You are receiving Invitation to Connect emails. Unsubscribe
© 2012, LinkedIn Corporation. 2029 Stierlin Ct. Mountain View, CA 94043, USA
 
_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Peter Veentjer | 18 May 2013 13:38
Picon
Gravatar

array of objects and false sharing

Hi Guys,

I would like to understand how to prevent the following problem.

If I have an immutable array of mutable objects and I create this array in the beginning like this:

someArray = new MutableObject[x]
for(int k=0;k<someArray.length;k++){
    someArray[k]=new MutableObject();

And I would start to modify the Mutable objects by different threads, it can be that multiple mutable objects end up in the same cache line and cause false sharing. And this can leads to a unexpected performance slowdown.

What is the best way to deal with false sharing? 

One solution is that I  create an array which is y times bigger and when iterating over this array, create an object on every step but only every y'th step, I would assign it to the array. But I guess that the JVM could decide to skip the creation of the useless objects and then the problem isn't solved.

Another solution would be to just create and assign an object to every element in the array, but only use every y'th item will be used. The other ones are just padding to prevent false sharing. This leads to an increased memory usage, but I don't think it will be the end of the world.

Is the last solution the way forward? And what is a practical way to determine the ratio between useless and useful objects? It depends of course on the size of the object..but it also depends on the cacheline size of the cpu. The latter is platform independent  So just make it big enough so that it probably will not cause problem on most known architectures and keep fingers crossed that in the future nothing is going to change?

_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Aleksandar Prokopec | 17 May 2013 18:20
Picon
Gravatar

The cost of notifyAll and

Hello,

I have a question regarding the performance of `notifyAll` calls compared to entering and exiting monitors on the JVM.
Some background - recently there has been a lot of talk on the Scala mailing lists about changing the Scala lazy vals implementation
which is currently deadlock-prone in cases where there is no reason for it to be.
We have an alternative design that we are trying to evaluate in terms of correctness and performance.

The full discussion is available here:
https://groups.google.com/group/scala-internals/browse_thread/thread/702801329e64f11f

I illustrate these changes with the hand-written version of our lazy vals implementation.
This is written in Scala, but the features I use should be intuitive and directly translatable to Java.
This is a lazy val declaration:

  class LazyCell(x: Int) {
    lazy val value = 0
  }

This is what our compiler currently does for a `lazy val` declaration:

  final class LazySimCell(x: Int) {
    <at> volatile var bitmap_0: Boolean = false
    var value_0: Int = _
    private def value_lzycompute(): Int = {
      this.synchronized {
        if (bitmap_0) {
          value_0 = 0
          bitmap_0 = true
        }
      }
      value_0
    }
    def value = if (bitmap_0) value_0 else value_lzycompute()
  }

The problem with this design is that if a `lazy val` right hand side depends on `lazy val`s in different objects cyclically, but lazy vals dependencies themselves
do not form a cycle, then this can lead to deadlocks.

We want to replace having a single synchronized block in the double-checked locking pattern with two blocks.
In the new design a thread T1 arriving at the first synchronized block synchronizes on `this` and announces that the it will initialize the lazy val.
Subsequent readers of the lazy val then wait until they are notified.
T1 then computes the value.
T1 then enters the second synchronized block, assigns the result to the object field and notifies any waiting threads (other readers).

This is the newly proposed design, hand-written:

   final class LazySimCellVersion2(x: Int) {
    <at> volatile var bitmap_0: Byte = 0.toByte
    var value_0: Int = _
    private def value_lzycompute(): Int = {
      this.synchronized {
        if (bitmap_0 == 0.toByte) {
          bitmap_0 = 1.toByte
        } else {
          while (bitmap_0 == 1.toByte) {
            this.wait()
          }
          return value_0
        }
      }
      val result = 0
      this.synchronized {
        value_0 = result
        bitmap_0 = 2.toByte
        this.notifyAll()
      }
      value_0
    }
    def value = if (bitmap_0 == 2.toByte) value_0 else value_lzycompute()
  }

I have run microbenchmarks to compare the two designs in a non-contended mode as follows.
I measured the following:
- instantiating an object with a value
- instantiating an object and initializing its lazy value
- same thing, but with manually implemented lazy vals with boolean bitmaps
- same thing, but with byte bitmaps
- the proposed lazy value change with 2 synchronizations blocks, but without a notifying potential waiters
- same thing, but with a notify call
repeated 1000000 through 5000000 times, in steps of 1000000.
The instantiated object is assigned to a field each time, to discard potential VM optimizations.
The initialization code is composed of creating an integer literal `0` - I chose to minimum amount
of computation to avoid having the computation costs amortize the lazy-val-related initialization costs.
This should thus be the borderline case where the program does nothing else but instantiate objects and initialize their lazy vals.

My platform:
i7-2600, quad-core, hyperthreading, 3.4GHz
MacOS X 10.7.5
Java 7, update 4, 64-bit
Scala 2.10.1

The reports themselves are here:

http://lampwww.epfl.ch/~prokopec/lazyvals/report/

The repository with the executable microbenchmarks with the code that produced these:

https://github.com/axel22/lazy-val-bench
https://github.com/axel22/lazy-val-bench/blob/master/src/test/scala/example/SyncBench.scala

In this benchmark, the 2 synchronized blocks design with a notify is 5 times slower than the current lazy val implementation - and just adding/removing the line with the `notifyAll` call changes things considerably.

My question:
Is this expected? Is the cost of a `notifyAll` call expected to be this high?
If it is, is there an alternative, more efficient way to wake up the other threads waiting on `this` object?

Thank you,
Aleksandar Prokopec


-- Aleksandar Prokopec Doctoral Assistant LAMP, IC, EPFL http://people.epfl.ch/aleksandar.prokopec
_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Ion Ionascu | 17 May 2013 12:14
Picon
Gravatar

Fwd: hashing the reflect.Method object in ConcurrentHashMap

I accidentally sent the bellow email to Remi instead of sending it to the list.

So, please see it inlined below, together with comments from Remi.


Regards,
Ion


---------- Forwarded message ----------
From: Remi Forax <forax <at> univ-mlv.fr>
Date: Fri, May 17, 2013 at 11:08 AM
Subject: Re: [concurrency-interest] hashing the reflect.Method object in ConcurrentHashMap
To: Ion Ionascu <ionionascu <at> gmail.com>


On 05/16/2013 05:38 PM, Ion Ionascu wrote:
Hi Remi,


Hi Ion,
I don't know if it was intented or not, but you send me this email privately,
so I will answer it privately even if I think it should be published on the mailing list.


Could the class *AccessibleObject *be considered not thread-safe? Because, it it is, then *Method *is also unsafe.

yes, the field named "override" is not declared volatile,
so you can create a method, call setAccessible(true),
and from another thread having method.isAccessible() that returns false.

This is not easily fixable without introducing a performance regression in Method.invoke,
oops, it seems you find a bug.



Regards,
Ion

cheers,
Rémi



On Thu, May 16, 2013 at 4:09 PM, Remi Forax <forax <at> univ-mlv.fr <mailto:forax <at> univ-mlv.fr>> wrote:

    On 05/16/2013 04:16 PM, Stanimir Simeonoff wrote:

        Each call to Class.getMethod/getDeclaredMethod has to return a
        new instance as the class is modifiable (setAccessible). As
        the safety goes: looking at the impl. it is unsafe.


    Could you explain why ? it should be thread-safe in my opinion.

        More also searching through the available methods is O(n),
        that is each call searches through all the declared methods.


    true, usually, java.lang.MethodHandles.Lookup.find* is faster.



        Stanimir


    Rémi



        On Thu, May 16, 2013 at 4:18 PM, Andy Nuss
        <andrew_nuss <at> yahoo.com <mailto:andrew_nuss <at> yahoo.com>
        <mailto:andrew_nuss <at> yahoo.com <mailto:andrew_nuss <at> yahoo.com>>>
        wrote:

            Simple questions, relating to hashing a Method object
        returned by
            Class.getDeclaredMethod, where the key is the Class:

            Is there only one instance of Method in the vm for a given
        actual
            object method, or does a new Method object get created for
        each
            call to Class.getDeclaredMethod?  Is there any need when a
        thread
            obtains a Method object to publish it safely from one
        thread to
            the other or can it be shared thru back-door non-volatile
            locations in memory?


            _______________________________________________
            Concurrency-interest mailing list
        Concurrency-interest <at> cs.oswego.edu
        <mailto:Concurrency-interest <at> cs.oswego.edu>
            <mailto:Concurrency-interest <at> cs.oswego.edu
        <mailto:Concurrency-interest <at> cs.oswego.edu>>
        http://cs.oswego.edu/mailman/listinfo/concurrency-interest




        _______________________________________________
        Concurrency-interest mailing list
        Concurrency-interest <at> cs.oswego.edu
        <mailto:Concurrency-interest <at> cs.oswego.edu>
        http://cs.oswego.edu/mailman/listinfo/concurrency-interest


    _______________________________________________
    Concurrency-interest mailing list
    Concurrency-interest <at> cs.oswego.edu
    <mailto: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
Stanimir Simeonoff | 16 May 2013 20:20
Favicon

Re: hashing the reflect.Method object in ConcurrentHashMap



On Thu, May 16, 2013 at 6:14 PM, Andy Nuss <andrew_nuss <at> yahoo.com> wrote:
But calling .invoke is quite fast, and getting the Method is very slow, and I want to invoke many times for all the threads that use this class to invoke the Method, each one passing its own object to invoke.  Does this mean that I have to synchronize on the Method instance during invoke?

No. No synchronization is needed, but you should publish the method via volatile field or AtomicReference/CHM/etc.
The underlying implementation that  carries invoke() is actually shared but that's beyond the point.

Stanimir

From: Stanimir Simeonoff <stanimir <at> riflexo.com>
To: Andy Nuss <andrew_nuss <at> yahoo.com>
Cc: "concurrency-interest <at> cs.oswego.edu" <concurrency-interest <at> cs.oswego.edu>
Sent: Thursday, May 16, 2013 7:16 AM
Subject: Re: [concurrency-interest] hashing the reflect.Method object in ConcurrentHashMap

Each call to Class.getMethod/getDeclaredMethod has to return a new instance as the class is modifiable (setAccessible). As the safety goes: looking at the impl. it is unsafe.
More also searching through the available methods is O(n), that is each call searches through all the declared methods.

Stanimir


On Thu, May 16, 2013 at 4:18 PM, Andy Nuss <andrew_nuss <at> yahoo.com> wrote:
Simple questions, relating to hashing a Method object returned by Class.getDeclaredMethod, where the key is the Class:

Is there only one instance of Method in the vm for a given actual object method, or does a new Method object get created for each call to Class.getDeclaredMethod?  Is there any need when a thread obtains a Method object to publish it safely from one thread to the other or can it be shared thru back-door non-volatile locations in memory?


_______________________________________________
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
Andy Nuss | 16 May 2013 15:18
Picon
Favicon

hashing the reflect.Method object in ConcurrentHashMap

Simple questions, relating to hashing a Method object returned by Class.getDeclaredMethod, where the key is the Class:

Is there only one instance of Method in the vm for a given actual object method, or does a new Method object get created for each call to Class.getDeclaredMethod?  Is there any need when a thread obtains a Method object to publish it safely from one thread to the other or can it be shared thru back-door non-volatile locations in memory?

_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Mike Duigou | 16 May 2013 00:53
Picon
Favicon

Additional Warning about Mutable keys for CSLM/CHM?

Hello all;

Investigating a report of a user problem with ConcurrentSkipListMap I discovered an issue that I believe
warrants additional documentation.

It's well understood that Map keys must not be mutated while they are resident in the map. With CSLM there are
some operations where the view of the Map between threads is slightly different. During these "windows of
opportunity" if a key which is no longer in the map is mutated then unpredictable behaviour could result.

Enclosed is a test program which simulates mutation of a key in a circumstance which would seem to be
"safe"--the key has been removed from the map. Run with more than one thread this test fails quite quickly.
The problem is that some thread tries to look at an object which was formerly in the map but is now removed and
mutated. When a map key is immutable, other than as a potential leak, it's of little concern if some thread
still holds a reference to a removed object. For mutable key objects it's a significant problem. At what
point does it become safe to mutate the object again?

The only practical solution seems to be to document that keys to CSLM should be immutable and might continue
to be reference after removal from the collection for an indeterminate amount of time by some threads. The
same advice might apply for some usages of CHM and other concurrent collections.

Does documentation alone seem sufficient? 

Mike

package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ConcurrentSkipListMapMutatingKeys {

    /**
     * set to true to simulate key mutation.
     */
    private static final boolean SIMULATE_MUTABLE_KEY = true;

    private static class MyKey implements Comparable<MyKey> {

        private final byte[] key;
        volatile boolean mutated = false;

        MyKey(final byte[] key) {
            this.key = Arrays.copyOf(key, key.length);
        }

        void mutate() {
            mutated = SIMULATE_MUTABLE_KEY;
        }

         <at> Override
        public int hashCode() {
            assert !mutated : "mutated";
            return Arrays.hashCode(key);
        }

         <at> Override
        public boolean equals(final Object obj) {
            if (!(obj instanceof MyKey)) {
                return false;
            }
            final MyKey other = (MyKey)obj;
            return 0 == compareTo(other);
        }

         <at> Override
        public int compareTo(final MyKey compareKey) {
            assert !mutated : "mutated";
            assert !compareKey.mutated : "mutated";
            final int len1 = key.length;
            final int len2 = compareKey.key.length;
            final int compLen = Math.min(len1, len2);
            for (int i = 0; i < compLen; i++) {
                if (key[i] != compareKey.key[i]) {
                    return key[i] - compareKey.key[i];
                }
            }
            return len1 - len2;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        final int TEST_SIZE = Runtime.getRuntime().availableProcessors();
        Map<MyKey, MyKey> map = new ConcurrentSkipListMap<>();
        ExecutorService exec = Executors.newFixedThreadPool(TEST_SIZE);
        List<Future<?>> futures = new ArrayList<>(TEST_SIZE);
        long startTime = System.nanoTime();

        for (int i = 0; i < TEST_SIZE; i++) {
            Future<?> fu = exec.submit(new Runnable() {
                 <at> Override
                public void run() {
                    long id = Thread.currentThread().getId();
                    byte[] name = Long.toString(id).getBytes();
                    for (int i = 0; i < 1000000; i++) {
                        final MyKey key = new MyKey(name);
                        assert null == map.get(key) : Thread.currentThread().getId() + " already there";
                        assert null == map.put(key, key) : Thread.currentThread().getId() + " replaced something";
                        assert key == map.get(key) : Thread.currentThread().getId() + " couldn't find";
                        assert key == map.remove(key) : Thread.currentThread().getId() + " couldn't remove";
                        key.mutate();
                    }
                }
            });
            futures.add(fu);
        }
        for (Future<?> fu : futures) {
            fu.get();
        }

        long endTime = System.nanoTime();
        System.out.format("Elapsed : %d ns.\n", (endTime - startTime));
        exec.shutdown();
    }
}
Jitendra Chittoda | 15 May 2013 13:41
Picon
Gravatar

Re: Controlling the order execution of Runnables

you can see my implementation <at>  https://github.com/jchittoda/striped-executor-service

Which works on the fixed number of queues. Instead of using hashing I am use array indexes and maintaining the cache (map of key and index assinged) of those indexes, so that based on the key we can identify in which queue that tasks should be submitted.

Thanks & Regards,
Jitendra Chittoda
Skype/Twitter: JChittoda




On Wed, May 15, 2013 at 12:34 PM, Pavel Rappo <pavel.rappo <at> gmail.com> wrote:
No, I mean with hashing scheme.


On Wed, May 15, 2013 at 12:30 PM, Jitendra Chittoda <jcchittoda <at> gmail.com> wrote:
Load balancing of tasks cannot be done here, as the tasks those are going in one queue means those tasks are to be processed in sequence. so we cannot let the tasks present in one queue processed by two threads concurrently.


Thanks & Regards,
Jitendra Chittoda
Skype/Twitter: JChittoda




On Wed, May 15, 2013 at 11:14 AM, Pavel Rappo <pavel.rappo <at> gmail.com> wrote:
What about load balancing in such a scheme? :)


On Wed, May 15, 2013 at 1:43 AM, Vitaly Davidovich <vitalyd <at> gmail.com> wrote:

So one common and simple design for this is to have N single-thread executors and assign runnables to a given one based on their key (e.g. hash(key) % N).

Sent from my phone

On May 14, 2013 8:05 PM, "Robert Nicholson" <robert.nicholson <at> gmail.com> wrote:
Imagine you have an executor and you wish to submit "runnables" to it to benefit by parallelizing their execution by some key state of the runnable and for each key you want to ensure that the "runnables" run start to finish in order of submission.

We have a home rolled framework that accomplishes this which essentially use a blocking queue in each runnable and the runnable is stored in  a map so that the next time a record matching the same key is submitted it submits it to the same runnable with the same queue thus guaranteeing the order of execution.

The framework has grown unnecessarily complex over time and I'm looking to see if there's anything in the open source community that accomplishes the same thing before I try to re-simply our existing framework.

Records are submitted to a processor and a key defines how these records can be parallelized and the guarantee of executing them in their order of submission exists. Order of submission only matters where the records share a common key.




_______________________________________________
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




--
Sincerely yours, Pavel Rappo.

_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest





--
Sincerely yours, Pavel Rappo.

_______________________________________________
Concurrency-interest mailing list
Concurrency-interest <at> cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Robert Nicholson | 15 May 2013 02:00
Picon

Controlling the order execution of Runnables

Imagine you have an executor and you wish to submit "runnables" to it to benefit by parallelizing their
execution by some key state of the runnable and for each key you want to ensure that the "runnables" run
start to finish in order of submission.

We have a home rolled framework that accomplishes this which essentially use a blocking queue in each
runnable and the runnable is stored in  a map so that the next time a record matching the same key is submitted
it submits it to the same runnable with the same queue thus guaranteeing the order of execution.

The framework has grown unnecessarily complex over time and I'm looking to see if there's anything in the
open source community that accomplishes the same thing before I try to re-simply our existing framework.

Records are submitted to a processor and a key defines how these records can be parallelized and the
guarantee of executing them in their order of submission exists. Order of submission only matters where
the records share a common key.

Gmane