Threads Flashcards

1
Q

What does thread mean in Java?

A

Means two different things:

  • An instance of class java.lang.Thread
  • A thread of execution
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How threads work in terms of memory?

A

Each thread has a separate call stack. main( ) has the main thread.

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

How does different JVM’s work for giving turns to threads?

A

Different JVM’s work in different ways. One might use round-robin fashion the other might not give turn to others until one finishes.

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

How does a thread begin in Java?

A

It begins as an instance of java.lang.Thread

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

Explain run( ) method

A

The job that needs to be done in the separate thread goes into run. It is either in java.lang.Thread or in the implementation of Runnable interface.

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

How does extending Thread class works?

A

You have to override run method i.e. public void run()
You can overload it but it will be ignored and even if you call it yourself it won’t have a separate call stack. But it is not a good design choice. And on a separate note - Thread itself extends Runnable.

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

How does implementing Runnable works?

A

You implement Runnable and override run i.e. public void run()

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

How do we instantiate a thread that extends Thread?

A
It is simple. Just;
MyThread t = new MyThread();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do we instantiate a thread that implements Runnable?

A

This time we need worker and job classes. Thread is the worker that runs the thread-specific code and Runnable is the job class that runs the job that needs to be done.
First instantiate;
MyRunnable r = new MyRunnable();
Next get instance of Thread and give your runnable;
Thread t = new Thread(r);
The Runnable you pass to the Thread constructor is called the target or the target Runnable.

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

What happens when no args are passed to Thread()?

A

Thread calls its own run( ) method.

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

What happens when same target is passed to multiple Threads?

A

You can pass a single Runnable instance to multiple Thread objects so that the same Runnable becomes the target of multiple threads.Giving the same target to multiple threads means that several threads of execution will be running the very same job (and that the same job will be done multiple times)

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

What are some thread constructors?

A
  • Thread()
  • Thread(Runnable target)
  • Thread(Runnable target, String name)
  • Thread(String name)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do we start a thread?

A

t.start();

before start is called the thread is said to be in new state. We start a Thread not a Runnable.

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

What happens when start is called?

A
  • A new thread of execution starts (with a new call stack).
  • The thread moves from the new state to the runnable state.
  • When the thread gets a chance to execute, its target run() method will run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Does this code start a new call stack?
Thread t = new Thread();
t.run();

A

No. Calling run in Runnable does not start a new call stack.

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

How can we print name of a Thread?

A

We can call getName() method of the thread that executes the that Runnable’s run() method. But we do not have a reference to current thread, so that’s how it is done:
Thread.currentThread().getName()

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

Does a thread still has a name even if we do not name it?

A

Yes. For main thread its “main” and for other threads its like “Thread-0”

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

What happens when a thread completes its run() method?

A

The stack for that thread dissolves and the thread is considered dead. It’s still a thread object and methods on that object can be invoked as any other Java object. But it’s not a thread of execution any more. And we can not call start() on that object again.

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

What happens when we try to start a Thread second time?

A

It can not be started and IllegalThreadStateException is thrown.

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

What does getId() method returns when invoked on a thread?

A

It returns the id of thread. It’s positive, unique, long and a thread’s only id for the thread’s entire life.

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

What is thread scheduler?

A

It’s part of JVM and decides which thread is going to actually run from all of the eligible ones i.e. in runnable state. And also decides which will be out of the run state.

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

In which order threads are chosen by thread scheduler?

A

The order in which runnable threads are chosen to run is not guaranteed.

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

What are thread states?

A
  • New
  • Runnable
  • Running
  • Waiting/blocked/sleeping
  • Dead
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Define “New” thread state

A

The state after Thread is instantiated. It’s a thread object but not a thread of execution yet. start() method has not been invoked yet. It is not alive.

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

Define “Runnable” thread state

A

The thread is eligible to run but not selected by scheduler yet. It can be after start() is called or returned back from a blocked, waiting or sleeping state. It’s considered alive.

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

Define “Running” thread state

A

When a runnable is selected by scheduler from thread pool. That’s the only way to be in running state.

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

Define “Waiting/blocked/sleeping” thread state

A

The thread is alive but not eligible to run in this state. It can blocked waiting for a resource or it might be sleeping by the code.

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

Define “Dead” thread state

A

When a thread completes the thread’s state is dead and can not be brought back to life. If start() is invoked on this thread. runtime exception is thrown.

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

Define “Sleeping” state details

A

sleep() is a static method and can be called from code

Thread.sleep(). sleep can throw checked InterruptedException

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

How does timer is Thread.sleep() works?

A

It makes the current thread sleep “at least” for the specified time. It returns back to runnable after time finishes but it might not be returned back to running by scheduler. It’s a static method and one thread can not put another one into sleeping.

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

Do threads have any priorities?

A

Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases, the range is less than 10). The scheduler in most JVMs uses preemptive, priority-based scheduling (which implies some sort of time slicing). This does not mean that all JVMs use time slicing. In most cases, the running thread will be of equal or greater priority than the highest-priority threads in the pool. But never rely on thread priorities since it is not guaranteed.

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

How is thread priority set?

A

By default a thread gets the priority of the thread that creates it. Or it can be set by calling setPriority() on the thread object. JVM will never change a priority. And 1-10 is not guaranteed since some JVM’s have range 1-5.In that case different priorities might be mapped to same one.

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

How does yield() work?

A

When a thread calls yield, it goes from running to runnable to give turn to other same priority threads. But the behaviour is not guaranteed!

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

How does join() work?

A

A thread is joined to end of another thread. If you join B to A, B is executed when run() of A completes and A becomes dead.

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

What does the code below mean?
Thread t = new Thread();
t.start();
t.join();

A

“Join me (the current thread) to the end of t, so that t must finish before I (the current thread) can run again.”

You can also call one of the overloaded versions of join() that takes a timeout duration so that you’re saying, “wait until thread t is done, but if it takes longer than 5,000 milliseconds, then stop waiting and become runnable anyway.”

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

Define other ways where a thread can leave running state?

A
  • The thread’s run() method completes.
  • A call to wait() on an object (we don’t call wait() on a thread).
  • A thread can’t acquire the lock on the object whose method code it’s attempting to run.
  • The thread scheduler can decide to move the current thread from running to runnable in order to give another thread a chance to run. No reason is needed—the thread scheduler can trade threads in and out whenever it likes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is a race condition?

A

Multiple threads can access the same resource (typically an object’s instance variables) and can produce corrupted data if one thread “races in” too quickly before an operation that should be “atomic” has completed.

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

How to protect data from race conditions?

A
  • Mark the variables private

* Synchronize the code that modifies the variables

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

How does synchronized keyword works?

A

Once a thread starts the sync block another thread cannot enter the method until the first one completes the process by exiting the method.

40
Q

Tell about object locks in java

A

Every object in Java has a built-in lock that comes into play when the object has sync method code.

41
Q

What happens when we enter a sync code block?

A

When we enter a synchronized non-static method, we automatically acquire the lock associated with the current instance of the class whose code we’re executing (the this instance). Acquiring a lock for an object is also known as getting the lock, or locking the object, locking on the object, or synchronizing on the object.

42
Q

Can a thread get the lock of an object when another thread is holding the lock?

A

No

43
Q

How the lock on an object is released?

A

When the thread holding the lock exits the sync block.

44
Q

Can variables or classes be synchronized?

A

No. Only methods (or blocks) can be synchronized, not variables or classes.

45
Q

How many locks each object has?

A

Each object has just one lock.

46
Q

Can a class have both sync and non-sync methods?

A

Yes. Not all methods in a class need to be synchronized. A class can have both synchronized and non-synchronized methods.

47
Q

Can two separate threads execute sync methods of a class at the same time?

A

No. Once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class (for that object).

48
Q

Can multiple threads access an object’s non-sync methods?

A

If a class has both synchronized and non-synchronized methods, multiple threads can still access the class’s non-synchronized methods!

49
Q

When a thread goes to sleep does it release the locks?

A

No. If a thread goes to sleep, it holds any locks it has—it doesn’t release them.
And its locks will be unavailable to other threads.

50
Q

Can a thread acquire more than one lock?

A

Yes. Also, if a thread acquires a lock and then attempts to call a synchronized method on that same object, no problem. The JVM knows that this thread already has the lock for this object, so the thread is free to call other synchronized methods on the same object, using the lock the thread already has.

51
Q

Can you sync a block of code?

A

You can synchronize a block of code rather than a method.

52
Q

Which object’s lock you acquire in sync block?

A

When you synchronize a block of code, you specify which object’s lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code.

53
Q

What’s the difference between these two code blocks?
public synchronized void doStuff() {
System.out.println(“synchronized”);
}

public void doStuff() {
synchronized(this) {
System.out.println("synchronized");
}
}
A

They both get the lock on the object that owns the method.

54
Q

Can static methods be sync.ed?

A

Yes. In that case you acquire the lock for the class.

55
Q
What does that code block do?
public static int getCount() {
synchronized(MyClass.class) {
return count;
}
}
A
MyClass.class is called a class literal.It's a special feature in the Java language that tells the compiler (who tells the JVM): Go and find me the instance of Class that represents the class called MyClass. You can also do this with the following code:
public static void classMethod() throws ClassNotFoundException {
Class cl = Class.forName("MyClass");
synchronized (cl) {
// do stuff
}
}
56
Q

What happens if a thread can’t get the lock - i.e. gets blocked on the object’s lock?

A

Essentially, the thread goes into a kind of pool for that particular object and has to sit there until the lock is released and the thread can again become runnable/running.

57
Q

Can a static and non-static sync method block each other?

A

No. The static method locks on a Class instance, while the non-static method locks on the this instance— these actions do not interfere with each other at all.

58
Q

What’s the lock behavior of Thread methods?

A

wait() gives up locks whereas notify(), join(), sleep(), and yield() keep the locks.

59
Q

What is a thread-safe class?

A

When a thread protects its data we say the class is thread safe.

60
Q

If a class is Thread-safe does that mean that it is always thread safe?

A

No. In a “thread-safe” class like the one returned by synchronizedList(), each individual method is synchronized. So names.size() is synchronized, and names.remove(0) is synchronized. But nothing prevents another thread from doing something else to the list in between those two calls. And that’s where problems can happen.

61
Q

What is a thread deadlock?

A

Deadlock occurs when two threads are blocked, with each waiting for the other’s lock. Neither can run until the other gives up its lock, so they’ll sit there forever.

62
Q

Give an example to thread lock.

A
public class DeadlockRisk {
private static class Resource {
public int value;
}
private Resource resourceA = new Resource();
private Resource resourceB = new Resource();
public int read() {
synchronized(resourceA) { // May deadlock here
synchronized(resourceB) {
return resourceB.value + resourceA.value;
}
}
}
public void write(int a, int b) {
synchronized(resourceB) { // May deadlock here
synchronized(resourceA) {
resourceA.value = a;
resourceB.value = b;
}
}
}
}
63
Q

What can be a way to prevent deadlocks?

A

There are design approaches that can help avoid deadlock, including strategies for always acquiring locks in a predetermined order.

64
Q

Can wait() and notify() be called from any context?

A

wait(), notify(), and notifyAll() must be called from within a synchronized context! A thread can’t invoke a wait or notify method on an object unless it owns that object’s lock.

65
Q

How wait() method on Object works?

A

A thread gets on an object’s waiting list by executing the wait() method of the target object.

66
Q

What happens when notify() method of the target object is called?

A

If many threads are waiting on the same object, only one will be chosen (in no guaranteed order) to proceed with its execution. If there are no threads waiting, then no particular action is taken.

67
Q
What does the below code do?
synchronized(anotherObject) { 
	try {
		anotherObject.wait();
	} catch(InterruptedException e){}
}
A
synchronized(anotherObject) { // this has the lock on anotherObject
	try {
		anotherObject.wait();
		// the thread releases the lock and waits
		// To continue, the thread needs the lock,
		// so it may be blocked until it gets it.
	} catch(InterruptedException e){}
}
For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object. When the thread waits, it temporarily releases the lock for other threads to use, but it will need it again to continue execution.
68
Q

When the lock on the object is released after wait is called?

A

When the wait() method is invoked on an object, the thread executing that code gives up its lock on the object immediately.

69
Q

When the lock on the object is released after notify is called?

A

When notify() is called, that doesn’t mean the thread gives up its lock at that moment. If the thread is still completing synchronized code, the lock is not released until the thread moves out of synchronized code. So just because notify() is called, this doesn’t mean the lock becomes available at that moment.

70
Q

When notifyAll is called how do the objects waitin for that lock behave?

A

All of the threads will be notified and start competing to get the lock. As the lock is used and released by each thread, all of them will get into action without a need for further notification.

71
Q

What is a spontaneous wakeup?

A

A thread may wake up even though no code has called notify() or notifyAll(). (At least, no code you know about has called these methods. Sometimes, the JVM may call notify() for reasons of its own, or code in some other class calls it for reasons you just don’t know.) What this means is that when your thread wakes up from a wait(), you don’t know for sure why it was awakened. By putting the wait() method in a while loop and rechecking the condition that represents what we were waiting for, we ensure that whatever the reason we woke up, we will re-enter the wait() if (and only if) the thing we were waiting for has not happened yet.

72
Q

What is an IllegalMonitorStateException?

A

Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor. It’s an unchecked exception.

73
Q

What should be done in sync. calls to protect shared data?

A

You should also make use of the required synchronization for the wait() and notify() calls to also protect whatever other data you’re sharing between threads.

74
Q

What should be done in sync. calls to protect shared data?

A

You should also make use of the required synchronization for the wait() and notify() calls to also protect whatever other data you’re sharing between threads.

75
Q

To which classes do those methods belong?

wait () 
notify() 
notifyAll() 
start() 
yield()
sleep()
join()
run()
A

Object:
wait ()
notify()
notifyAll()

Thread:
start() 
yield() // static
sleep() // static
join()

Runnable:
run()

76
Q

What happens if you call start() on Thread object more than once?

A

It will throw IllegalThreadStateException.

77
Q

What is a process?

A

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.

78
Q

How do processes communicate?

A

To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.

79
Q

What is the relation between processes and threads?

A

Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process — every process has at least one. Threads share the process’s resources, including memory and open files.

80
Q

What is an interrupt?

A

An indicator that states a thread should stop what it does and do smth. else.

81
Q

How can a thread send an interrupt to another one?

A

By invoking interrupt on Thread object.For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.

82
Q

How can an interrup be supported?

A

In the first method methods like sleep throws InterruptedException. We can handle by catching that. But if no method throwing that exc. is called then we can check Thread.interrupted() as a second method.

83
Q

How is interrupt mechanism implemented?

A

By using an internal flag known as interrupt status.

84
Q

How is interrupt status flag is set?

A

By calling Thread.interrupt

85
Q

How is interrupt status flag is cleared?

A

By calling Thread.interrupted or after InterruptedException is thrown.

86
Q

Does isInterrupted change interrupt status flag?

A

It is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

87
Q

How does sleep and join respond to an interrupt?

A

By exiting with an InterruptedException.

88
Q

What are the possible problems when two or more threads communicate?

A

Thread interference and memory consistency.

89
Q

What are the forms of Thread Contention?

A

Starvation and livelock.

90
Q

What is a thread interference?

A

Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap.

91
Q

What is a happens-before relationship?

A
  • Reads from and writes to other variables cannot be reordered to occur after a write to a volatile variable, if the reads / writes originally occurred before the write to the volatile variable. The reads / writes before a write to a volatile variable are guaranteed to “happen before” the write to the volatile variable. Notice that it is still possible for e.g. reads / writes of other variables located after a write to a volatile to be reordered to occur before that write to the volatile. Just not the other way around. From after to before is allowed, but from before to after is not allowed.
  • Reads from and writes to other variables cannot be reordered to occur before a read of a volatile variable, if the reads / writes originally occurred after the read of the volatile variable. Notice that it is possible for reads of other variables that occur before the read of a volatile variable can be reordered to occur after the read of the volatile. Just not the other way around. From before to after is allowed, but from after to before is not allowed.
92
Q

What can form a happens-before relationship?

A
  • The synchronized and volatile constructs, as well as the Thread.start() and Thread.join() methods
  • Each action in a thread happens-before every action in that thread that comes later in the program’s order.
  • An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
  • A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
  • A call to start on a thread happens-before any action in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join on that thread.
93
Q

Can constructors be synchronized?

A

No.

94
Q

(An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness, as we’ll see later in this lesson.

A

TODO

95
Q

When does Thread Contention occur?

A

When two or more threads try to access the same resource simultaneously and cause the Java runtime to execute one or more threads more slowly, or even suspend their execution.

96
Q

What is volatile visibility guarantee?

A
  • If Thread A writes to a volatile variable and Thread B subsequently reads the same volatile variable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.
  • If Thread A reads a volatile variable, then all all variables visible to Thread A when reading the volatile variable will also be re-read from main memory.