ConcurrentModificationException in Java Stream but not in for loop with counter - java-8

I am removing comment nodes with jsoup and found something I do not understand.
This code works:
Example 1:
private static void removeComments(Node node) {
for (int i = 0; i < node.childNodes().size();) {
Node child = node.childNode(i);
if (child.nodeName().equals("#comment"))
child.remove();
else {
removeComments(child);
i++;
}
}
But this code throws an ConcurrentModificationException:
Example 2
private static void removeComments(Node node) {
node.childNodes()
.forEach(n -> {
if (n.nodeName().equals("#comment")) {
n.remove();
} else {
removeComments(n);
}
});
}
I try to write short, easy to understand code, ternary operator not supporting two void returns already destroyed my "oneline" approach. What limitation did I hit with that strange behaviour?

ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with an Iterator.
You can't modify a List in a for/each loop, which is syntactic sugar around the Iterator as an implementation detail. You can only safely call .remove() when using the Iterator directly.
Calling .remove() inside the for/each loop modifies the contents, and the Iterator that is used behind the scenes sees this and throws this exception.
Read about How to Avoid ConcurrentModificationException when using an Iterator.

Related

How to create a custom Sonar rule to check if a method throws a certain exception?

So we want to check a certain method, say findOne() in certain java classes if it throws a specific exception or not. If it doesn't throw the exception, then an issue to be reported at method level.
We could use
public void visitThrowStatement(ThrowStatementTree tree)
but this only gets called when there is a statement that throws the exception, how can we check if it's not thrown?
You need to keep a context in your visitor to know in which method you are currently visiting throw statements.
Basically, if you are within a findOne method, then you will visit the code of the method, if it has a correct throw statement,then don't raise an issue but if it has not then raise an issue.
Something along the lines of (this is pseudo code and should of course be adapted but that will explain the concept):
LinkedList<MethodTree> stack;
int throwCount = 0;
void visitMethod(MethodTree methodTree) {
stack.push(methodTree);
throwCount = 0;
super.visitMethod(methodTree);
if(throwCount == 0) {
//raise Issue
}
}
void visit throwStatement(ThrowStatementTree tree) {
if(isCorrectExceptionThrown(tree)) {
throwCount++;
}
}

Unity/C# : How to execute a function after another function has finished its execution?

I've been trying to build a "event system" for a project that I'm working on . Here is how I'm doing it : I populate a list with reference to a gameObject and the functions that I need to execute from that gameObject . Then , when the "event" is triggered (in this case , when the player steps into a trigger collider) I just loop over the list and Invoke the functions inside it.
The problem with this is that every single function inside the list gets executed at the same time. This works fine in some cases but if I want to create a more cinematic event I need to have the ability to execute a function after the previous one has finished it's execution .Sadly I have no idea how to do that.
I've been reading a lot of the documentation of both Unity and C# about coroutines and delegates but I can't seem to wrap my head around all those things and find a way to do implement them on code .So I need your help with that :How can I achieve this?
1) use Invoke
private void BeginRace()
{
Invoke("WaveFlag", 0.5f);
Invoke("Beeps", 1.5f);
Invoke("CrowdBeginsCheer", 2f);
Invoke("CarsStartMoving", 2.2f);
}
2) use coroutine
private void BeginRace()
{
StartCoroutine(RaceSequence());
}
private IEnumerator RaceSequence()
{
yield return new WaitForSeconds(.5f);
WaveFlag();
yield return new WaitForSeconds(1f);
Beeps();
yield return new WaitForSeconds(.5f);
CrowBeginsCheer();
yield return new WaitForSeconds(.2f);
CarsStartMoving();
}
You must master both coroutines and Invoke. Be sure to simply use Invoke when possible. Avoid coroutines when you are just learning Unity. (Advanced essay on coroutines.)
3) "I need to wait until the previous function has ended before executing the following one"
a) EACH OF THOSE FUNCTIONS must be an IEnumerator
private IEnumerator ExplodeCar()
{
..
}
private IEnumerator CrowdReaction()
{
..
}
private IEnumerator WinningCelebration()
{
..
}
b) To call them one after the other, waiting for each to finish
private void Sequence()
{
StartCoroutine(Seq())
}
private IEnumerator Seq()
{
yield return StartCoroutine(ExplodeCar());
yield return StartCoroutine(CrowdReaction());
yield return StartCoroutine(WinningCelebration());
}
Footnotes
If you want to wait until the next frame, use:
yield return null;
if you have a "stack" of things you want to do each frame, just do this
void Update()
{
if (newItem = yourStack.Pop())
newItem();
}
if you have a "stack" of things you want to do waiting for each to finish,
void Start()
{
StartCoroutine(YourStackLoop());
}
private IEnumerator stackLoop()
{
while(true)
{
if (newItem = yourStack.Pop())
yield return StartCoroutine(newItem());
else
yield return new;
}
}
Note that Update and a coroutine are fundamentally the same thing, read and study on this.
Note in the example, use your own usual Push/Pop (or FIFO, or whatever you wish). If unfamiliar, search many QA on here.

Thread safe queue with front() + pop()

I have created a thread safe queue (see code). The class seems to work but now I want to make the combination front() plus pop() thread safe in such a way that a thread first gets the element and then for sure removes the same element. I can come up with some solutions but they are not elegant for the user side or the strong exception safety guarantee will be lost.
The first solution is that the user simply has to lock the ThreadQueueu than call front() and pop() and unlock the ThreadQueue. However, the whole idea of the class is that the user has not to mind about the thread safety.
The second solution is to lock the queue inside the overloaded function front() and only unlock it in pop(). However, in this case the user is not allowed to only call front() or pop(), not that user friendly..
The third option I came up with is to create a public function in the class (frontPop) which returns the front element and removes it. However in this case the exception safety is gone.
What is the solution which is both user friendly (elegant) and maintain the exception safety?
class ThreadQueue: private std::queue<std::string>
{
mutable std::mutex d_mutex;
public:
void pop()
{
lock_guard<mutex> lock(d_mutex);
pop();
}
std::string &front()
{
lock_guard<mutex> lock(d_mutex);
return front();
}
// All other functions
private:
};
The usual solution is to provide a combined front & pop that accepts a reference into which to store the popped value, and returns a bool that is true if a value was popped:
bool pop(std::string& t) {
lock_guard<mutex> lock(d_mutex);
if (std::queue<std::string>::empty()) {
return false;
}
t = std::move(std::queue<std::string>::front());
std::queue<std::string>::pop();
return true;
}
Any exceptions thrown by the move assignment happen before the queue is modified, maintaining the exception guarantee provided by the value type's move assignment operator.

D Analogue to C++ member-function-pointers, not necessarily delegates

I have been learning D, and am in particular very excited for it's Generic programming capabilities. Delegates are wonderful, and apparently they have completely replaced member-function-pointers, so I was stuck when I wanted to implement something like the following:
template <typename T>
void DispatchMethodForAll(std::vector<T*> & container, void (T::* func)(void))
{
for(typename std::vector<T*>::iterator it = container.begin(); it != container.end(); ++it)
(*it)->*func();
}
According to what I have learned of function pointers and delegates in D, is that neither of them can do this, since function pointers can only be declared for global functions, and delegates have to be bound to an object, there is no "partial delegate" that I can find. As seen here, I cannot use a delegate, since there is no single object that can be bound to the method that is to be called.
I know that I could do it with mixins, and essentially make it a macro. However this really doesn't sound D-like, and I figured there should be "The correct way"
You could still use a delegate here.
void DispatchMethodForAll(T)(T*[] container, void delegate(T*) action)
{
foreach (it; container)
action(it);
}
...
DispatchMethodForAll(container, (Foo* foo) { foo.func(); });
Example: http://www.ideone.com/9HUJa
you can take a page out of the std.algorithm to find out how it does that
void DispatchMethodForAll(alias func, T)(T container)
{
alias unaryFun!func _func
foreach (it; container)
_func(it);
}
btw a delegate can be bound to a struct and the compiler can create a custom struct from local (stack allocated) variables and define a delegate on that
this happens with
void foo(){
int[] array;
int i=0;
void bar(int a){
i+=a;
}
void DispatchMethodForAll(&bar)(array);
writeln(i);//prints the sum of array
}
bar is a delegate bound to a struct with (at least) a member i of type int of which the local variable i is an alias

FIFO queue synchronization

Should FIFO queue be synchronized if there is only one reader and one writer?
What do you mean by "synchronized"? If your reader & writer are in separate threads, you want the FIFO to handle the concurrency "correctly", including such details as:
proper use of FIFO API should never cause data structures to be corrupted
proper use of FIFO API should not cause deadlock (although there should be a mechanism for a reader to wait until there is something to read)
the objects read from the FIFO should be the same objects, in the same order, written to the FIFO (there shouldn't be missing objects or rearranged order)
there should be a bounded time (one would hope!) between when the writer puts something into the FIFO, and when it is available to the reader.
In the Java world there's a good book on this, Java Concurrency In Practice. There are multiple ways to implement a FIFO that handles concurrency correctly. The simplest implementations are blocking, more complex ones use non-blocking algorithms based on compare-and-swap instructions found on most processors these days.
Yes, if the reader and writer interact with the FIFO queue from different threads.
Depending on implementation, but most likely. You don't want reader to read partially written data.
Yes, unless its documentation explicitly says otherwise.
(It is possible to implement a specialized FIFO that doesn't need synchronization if there is only one reader and one writer thread, e.g. on Windows using InterlockedXXX functions.)
Try this code for concurrent fifo usage:
public class MyObjectQueue {
private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private static final ReadLock readLock;
private static final WriteLock writeLock;
private static final LinkedList<MyObject> objects;
static {
readLock = lock.readLock();
writeLock = lock.writeLock();
objects = new LinkedList<MyObject>();
}
public static boolean put(MyObject p) {
writeLock.lock();
try {
objects.push(p);
return objects.contains(p);
} finally {
writeLock.unlock();
}
}
public static boolean remove(MyObject p) {
writeLock.lock();
try {
return objects.remove(p);
} finally {
writeLock.unlock();
}
}
public static boolean contains(MyObject p) {
readLock.lock();
try {
return objects.contains(p);
} finally {
readLock.unlock();
}
}
public MyObject get() {
MyObject o = null;
writeLock.lock();
try {
o = objects.getLast();
} catch (NoSuchElementException nse) {
//list is empty
} finally {
writeLock.unlock();
}
return o;
}
}

Resources