Programming Stuff Flashcards

1
Q

Give two ways two implemement the forking part of a fork/join code.

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are three ways of implementing a thread safe counter?

A

1) With synchronized keyword
2) With AtomicInteger
3) Using the reentrant lock

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why do we need a try{} finally [] block when using reentrant locks?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What library is used to implement TAS and CAS? And what methods are there?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give a barrier implementation of the following code segment. It needs to be reusable. Calling await() will put the threads into a blocked state.

A

Remember better solution is to do this in a while loop, because java can awaken threads at random.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly