What is the difference between StringBuffer and Stringuilder?
Answer: All the methods in StringBuffer are synchronized when necessary, while those in StringBuilder are not.
extended by java.lang.StringBuffer
All Implemented Interfaces:
Serializable, Appendable, CharSequence
StringBuffer class is safe for use by multiple threads.
The methods are synchronized where necessary so that all the operations on any particular instance behave
as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.
What is the purpose of the synchronizedList?
The method Collections.synchronizedList() returns a List whose methods are all
1)synchronized and 2) thread-safe according to the documentation.
What is true about the methods returned by the class synchronizedList()?
In a "thread-safe" class like the one returned by sychronizedList(), each individual method is synchronized.
How do you synchronize a method?
Place the "synchronized" keyword in front of the method.
What is Thread Deadlock?
Deadlock occurs when 2 threads are blocked, with each waiting for the other's lock.
Neither can run until the other gives up its lock, so they will sit forever.
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
For example, two threads T1 and T2 need a File and a Printer.
T1 acquires the lock for the file and is about to acquire the lock for the Printer but before it could acquire the lock,
T2 acquires the lock for the Printer and tries to acquire the lock for the file (which is already held by T1).
So now, both the threads keep waiting for ever for each other to release their locks and neither will be able to proceed.
What is the purpose of a) wait b) notify() and c) notifyAll()? Answer:
Java concurrency model uses locks to implement mutually exclusive access to objects in a multithreaded environment.
Locks are associated with every object in Java.
wait(), notify(), and notifyAll() methods are used by threads to communicate with each other while attempting to access a common object.
What must you take into consideration when using the methods wait(), notify(), and notifyAll()?
They must be called from within a synchronized method or block.
A thread cannot invoke methods wait or notify on an object unless it owns that object's lock.
To which class do wait() and notify() belong to?
These 2 methods belong to the Object class.
How does a thread get on the waiting list?
A thread gets on the waiting list by executing the wait() method of the target object.
What must be true for a thread to call
The thread has to be the owner of the lock for that object.