Java Threads Flashcards
Which library do we use to implement threads in Java?
java.lang.thread
What does the start() method do
method called to spawn a new thread
causes JVM to call run()
What does the interrupt() method do
freeze and throw exception to thread
Does calling run() start a thread?
NO! only start() starts a thread
how do you get the Thread ID
t.getId()
How do you set a thread name?
t.setName(…..)
How do you set Thread priority and what priorities can be set?
t.setPriority() Threads can have priority 1 through 10
how do you check if a thread is terminated?
What other states can be checked?
if (t.getState() == State.TERMINATED)
Other states:
new, runnable, blocked, waiting, time waiting or terminated
What is Coarse-grained locking?
Wrapping everything that remotely resembles a critical section into a lock
What is hand-over-hand locking in a linked list?
When a thread traverses the data structure, it lock each node when it first visits it and releases it once it has acquired the lock for the next node.
What is optimistic locking in the sense of a sorted linked list?
We itreate the data structure without taking any locks. Once we have found the required elements we lock them and check if everything is still correct.
If the state has changed while traversing and the operation cant be performed anymore we start over.
In optimistic locking we traverse the sorted linked list until reaching the required node and lock it. We only execute if the state hasnt changed. What conditions do we use to check the state? There are 2
1) The node to be operated on is stil reachable
2) the nodes predecessor is reachable and points to the node to be operated on
What do we need when we need to implement a .wait() somewhere? 2 things
.wait() is always in a synchronized block!
.wait() is always in a while loop!
What ca we say about the volatile keyword
when a variable is set as volatile it’s like telling the compiler that the variable is important and that everything that happens before that variable is used is visible to all threads.