I assume that the code that calls somefunction is passing in x.
Is the body of the loop doing anything to modify the TreeMap (or the pubKeys set)? The forEach loop uses the set's iterator, which will throw an exception on the NEXT use of the iterator after a change to the underlying collection, if the change is not made through the iterator - from TreeMap javadoc:
if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
Since you are using a forEach loop, you don't actually have access to the iterator it is using, so any changes you make to the collection will by definition not be through the iterator's remove method. Since it is the iterator that throws the exception, it will not be thrown until the next use of it, which is why the exception occurs on the forEach line, rather than within the body of the loop.