Programming Stuff Flashcards
Give two ways two implemement the forking part of a fork/join code.
1) easier way:
t1.fork();
t2.fork();
int count1 = t1.join();
int count2 = t2.join();
return count1 + count2;
2) “more efficient way”:
t1.fork();
count2 = f2.compute();
int count1 = t1.join();
return count1 + count2;
What are three ways of implementing a thread safe counter?
1) With synchronized keyword
2) With AtomicInteger
3) Using the reentrant lock
Why do we need a try{} finally [] block when using reentrant locks?
It is for deadlock prevention. Everything in the finally block happens no matter what happened before. So if the try cant execute finally will still happen
What library is used to implement TAS and CAS? And what methods are there?
java.util.concurrent.atomic.AtomicBoolean
with the methods:
boolean set(); boolean get(); boolean CompareAndSet(boolean expect, boolean update); boolean getAndSet(boolean newValue);
getAndSet is equal to TestAndSet
Give a barrier implementation of the following code segment. It needs to be reusable. Calling await() will put the threads into a blocked state.
Remember better solution is to do this in a while loop, because java can awaken threads at random.