Java Threads

Ace your homework & exams now with Quizwiz!

Consider the following class: public class Counter { private int count; public void increment(){ System.out.println(count++); } } If two threads call the increment() method on the same Counter instance simultaneously, which of the following are possible outputs? (Assume that there are no other calls to the Counter instance.) A. 0 1 B. 1 1 C. 0 0 D. 1 2

A. and C. are correct This is a straight forward implementation on an thread unsafe class. Observe that count is a shared resource that is accessed by multiple threads and there are multiple issues in this code: 1. Since access to count is not synchronized, there is no guarantee that changes made by thread 1 will even be visible to thread 2. Thus, both the threads may print 0 and increment it to 1 even if they run one after the other. To understand this point, you need to read about topic of visibility guarantee provided by the Java memory model. 2. count++ is not an atomic operation, which means that it can be broken up into three separate steps - 1. get the current value of count in cache 2. increment the cache value and 3. update the count with updated cache value. Now, for example, while thread 1 is about to execute step 3, thread 2 may come in and execute steps 1, 2, and 3. Thread 1 then executes the remaining step 3. The result is that value of count will be 1 after both the threads are done, while it should have been 2, and thus one increment operation is lost.

Given the following code: public class Valuator { public AtomicInteger status = new AtomicInteger(0); public void valuate() { int oldstatus = status.get(); /* valid code here */ int newstatus = //determine new status //INSERT CODE HERE } } Assuming that an instance of this class is shared among multiple threads, you want to update the status to newstatus only if the oldstatus has not changed. Which of the following lines of code will you use? A. status.compareAndSet(oldstatus, newstatus); B. status.compareAndSet(newstatus, oldstatus); C. status.setIfUnchanged(oldstatus, newstatus); D. status.setIfUnchanged(newstatus, oldstatus); E. if(oldstatus == status.get()) status.set(newstatus);

A. is correct. public final boolean compareAndSet(int expect, int update) Atomically sets the value to the given updated value if the current value == the expected value. Parameters: expect - the expected value update - the new value Returns: true if successful. if(oldstatus == status.get()) status.set(newstatus); This is valid code but is not thread safe. The value can potentially change after comparison and just befor it is set again. The whole point of using AtomicInteger is to make this operation atomic. compareAndSet is what you need to use.

onsider the following class: public class MySecureClass { public synchronized void doALotOfStuff() { try { LINE1: Thread.sleep(10000); }catch(Exception e){ } } public synchronized void doSmallStuff() { System.out.println("done"); } } Assume that there are two threads. Thread one is executing the doALotOfStuff() method and has just called LINE 1 and is sleeping. Now, Thread two decides to call doSmallStuff() method on the same object. What will happen? Select one: A. done will be printed immediately. B. done will not be printed until about 10 seconds. C. done will never be printed. D. An IllegalMonitorStateException will be thrown. E. An IllegalThreadStateException will be thrown.

B. is correct. This question is based on a simple concept that calling Thread.sleep() does not release the lock. In this case, the first thread acquires the lock for the object and goes to sleep for 10 seconds. Therefore, the second thread will not be able to get the lock to execute the second synchronized method until the first thread comes out of sleep (after 10 seconds) and releases the lock.

Which of the statements regarding the join() method of Thread class is correct? Select One: A. The thread calling the join() method must hold the lock of the other thread object. B. The thread object on which join() has to be called must be sleeping. C. The thread object on which join() has to be called must be waiting for a lock. D. none of these.

D. is correct. The thread that calls the join() method, pauses till the other thread ends (i.e. finishes its run() method.) There is no need for any thread to hold any lock.

Given: List<Student> sList = new CopyOnWriteArrayList<Student>(); Which of the following statements are correct? A. Student class must be Cloneable or Serializable. B. Student objects retrieved from sList are thread safe. C. Multiple threads can get Student objects from sList but can't add to it in a thread safe manner simultaneously. D. Multiple threads can safely add and remove objects from sList simultaneously. E. If a thread tries to add an object to it while another is iterating through the list, the second thread may get ConcurrentModificationException. F.You cannot add null to sList.

D. is correct. choice B - sList itself is thread safe, but it has no bearing on the objects stored in the list. So a Student object may or may not be thread safe depending on how it is coded. choice E - The iterator provided by this class first creates a copy of the list. Therefore, the thread that iterates through it will never get a ConcurrentModificationException even if another thread tries to modify the list. choice F - You can add null elements in CopyOnWriteArrayList (as well as in a regular ArrayList). Remember that HashMap supports adding null key as well as null values but ConcurrentHashMap does not.

Assume that Thread 1 currently holds the lock for an object (obj) for which 4 other threads, Thread 2 to 5, are waiting. Now, Thread 1 wants to release the lock but at the same time, it wants Thread 3 to get the lock. How will you accomplish this? Select one: A. Call t3.resume() after releasing the lock. B. Call t3.release() after releasing the lock. C. Instead of releasing the lock, call t3.acquire(obj); D. Instead of releasing the lock, call t3.notify(obj); E. None of these.

E. is correct. It is not possible to do so. Thread can only release the lock and it has no control over who gets the lock next. All the waiting threads compete to get the lock and any one of them can get it.

What should ideally be the return type of the method Callable from the package java.util.concurrent.Callable?

It should the data type of the return data that was input to the call() method. The Callable declaration interface is as follows: public interface Callable<V>{ V call() throws Exception; } Ex: public static class MyTask implements Callable<String>{ public String call(){ try { //do something } catch (Exception ex) { ex.printStackTrace(); } return "Data from callable"; } } Note that if you put Future as the return type of the call method, it would be technically a valid implementation. But it would not be appropriate. A Callable should return actual data object instead of wrapping the data into a Future. It is the job of ExecutorService.submit() method to return a Future that wraps the data returned by Callable.call(). For example: Future result = Executors.newSingleThreadExecutor().submit(new MyTask());


Related study sets

Managing Human Capital Chapter 1

View Set

Glycolysis and Gluconeogenesis II

View Set

COMPLETING THE APPLICATION, UNDERWRITING, AND DELIVERING THE POLICY

View Set

ATI Targeted Medical Surgical Neurosensory and Musculoskeletal

View Set

Организационные мероприятия при выполнении работ в электроустановках

View Set