Java Concurrency Review

¡Supera tus tareas y exámenes ahora con Quizwiz!

How do you make an object immutable? (3)

1) Declare all fields final 2) Prevent the object state from changing after construction. 3) Do not allow the "this" reference to escape

What are some ways to prevent the "this" reference to escape? (3)

1) Do not start a thread from the constructor, provide a start method instead 2) Use static inner classes whenever possible 3) Use a static factory method to return the instance and make the constructor private.

What are the advantages of using a private lock object instead of an object's intrinsic lock?

1) Encapsulation is a good thing. Encapsulating a lock object prevent clients from locking it, thus misused or liveness problems are less likely to happen. 2) Classes that use private locking are easy to analyze for thread safety (Verifying that a public lock is used consistently require analyzing the whole program).

How can you safely publish an object to other threads? (4)

1) Initializing it within a static initializer 2) Making the object immutable and assigning it to a final variable. 3) Declaring it as volatile or atomic reference 4) Using synchronized

What is it a good idea to declare fields final whenever possible? (2)

1) It conveys more info about the field 2) It makes it easy to analyze the different states an object can be in.

What is the difference between a latch and a barrier? (2)

1) Latches are for waiting for events while barriers are for waiting for Threads. 2) Barriers can be reutilized while latches cannot.

What are the types of thread confinement? (3)

1) Stack confinement 2) Ad hoc confinement 3) Thread Local

What are some problems of using wait, notify and notify for thread interaction and how to solve it? (2)

1) The JVM may awake a waiting thread unexpectedly 2) If a thread starts waiting after notify has been invoked, it'll wait forever Solutions: Use a while loop in order to go back to waiting if needed. Use a status flag to avoid waiting if it is not longer needed.

What are some ways to achieve thread safety? (3)

1) Thread confinement 2) Using synchronized 3) Delegating threadsafety to a thread-safe class.

What are the risks of accessing a variable without synchronization on a program? (2)

1) Threads may see partially updated objects or not see the update at all. 2) Processors make optimizations that can invert the order of operations.

What are some ways an object or its internal state can be published? (4)

1) Using the public modifier 2) Returning a private object from a public method 3) Passing the object to an alien method (an overridable method or a method in another class). 4) Allowing the "this" reference to escape

What object does a FutureTask wraps?

A Runnable or a Callable.

What happens if you use wait, notify or notifyAll outside of a synchronized context?

A RuntimeException will be thrown.

What is a Runnable?

A task that does not return a Result

What is a Callable?

A task that returns a Result.

What is a thread?

A thread is a java class. A thread of execution, on the other hand, is a separate subprocess that runs in the JVM.

How do use composition to add functionality to an existing thread-safe class?

Add another layer of synchronization, by creating synchronized methods that invoke the thread-safe class methods (Java Monitor Pattern).

What is an implicit requirement when using Collections.synchronizedXXX methods?

All subsequent access to the collection should be made through the wrapper.

What does it mean the "this" reference can escape?

An inner class has an implicit reference to the enclosing class. The "this: reference of the outer class seems to escape when it creates and publishes an instance of the inner class from its constructor. Other threads may access the inner class instance, which at the same time has access to the outer class private members, and since those members may not be properly initialized exceptions like NullPointer can be thrown.

What is Thread Confinement? (Confined Object).

Avoiding to share data with other threads so that synchronization is not needed. An object that is only accessed by one thread is said to be confined to that thread.

Why is it bad to breakdown synchronized blocks too far?

Because acquiring and releasing a lock has some overhead.

Why is that, confinement makes it easier to build thread-safe applications?

Because classes that confine their state can be analyzed without needing to check the whole program.

What is it inappropriate to catch InterruptedException and do nothing in response?

Because code higher up in the call stack wouldn't know interrupt was issued since the evidence gets lost.

Why synchronizing every method is not a good idea?

Because it may hurt perfomance.

Why is documentation important when it comes to thread safety?

Because maintainers of the code should know the synchronization strategy of a program in order to avoid violating it (Some subtle aspects of this strategy may not be noticed by maintainers).

Why is it recommended to avoid holding locks (synchronizing) during lengthy computations?

Because this affect performance and may live to liveness problems.

What's the proper way to ensure visibility when using synchronized?

Both read and write access to variables needs to be synchronized.

What are the disadvantages of using client-side locking or extending a thread-safe class to add new functionality?

Both strategies are tightly coupled to the class that's being used or extended. If that class changes its synchronization policy then client-side locking and subclasses will be affected.

What is a great advantage of bounded queues over unbounded ones?

Bounded queue make your program more robust since they have the capacity to block when there is more work than it can be handled.

How can you avoid race condition?

By ensuring compound actions are atomic.

What are some common types of race conditions? (2)

Check-then-act (like lazy initialization, Read-modify-write (increment operations).

Are constructor atomic?

Constructors can be considered atomic as long as you don't allow the "this" reference to escape. You cannot use synchronized on a constructor.

What is a defensive strategy to safely publishing mutable data?

Copying mutable data before return it.

What is a semaphore?

Counting semaphores are used to control the number of threads that can perform an action or used certain resources at a given time. This design pattern is used by thread pools.

What are the problems regarding visibility and stale data? (4)

Data corruption, unexpected exceptions, liveness issues and incorrect computations.

What are deques and what design pattern is supported by them?

Is a double ended blocking queue that allows efficient insertion and deletion from both the tail and the head of the queue. They support the work stealing design pattern.

What is the method wait for?

It is a blocking method, causes the current thread to temporarily release the lock of the object he is trying to wait on until another thread invokes notify or notifyAll on that object to continue its execution.

What is a FutureTask?

It is a cancellable asynchronous task. It has a get method that can be used to get the result and that will block until the computation is completed.

What is a BlockingQueue and what design pattern does it support?

It is a queue that can block either when queuing or dequeuing elements. There are bounded and unbounded queues. When a queue is bounded, the put method will block if the queue is full. On the other hand, for both bounded and unbounded queues, the take method will block when the queue is empty. It supports the producer-consumer design pattern.

What is a deadlock?

It is a runtime problem that occurs when two threads are waiting for each other to release a lock. They wait forever and no further progress is possible.

What is the yield method for?

It is a static method that causes the current thread to pauses its execution as an attempt to give other threads a chance to run. The current thread goes from Running to Runnable.

What is the sleep method for?

It is a static method that pauses the execution of the current thread for at least the given amount of milliseconds. When the time is over, the thread will go back to Runnable.

What is a latch ? Give an Example of a Latch.

It is a synchronizer that allows other threads to wait until other operations in other threads are completed. For example, CountDownLatch that allows threads to wait until the count reaches 0.

What is race condition?

It is a timing problem that occurs when two threads are accessing a mutable object and one of the threads "races in" and end up intervening in the other's thread way (messing up with an operation that was supposed to be atomic).

What is the join method for?

It is an instance method, that causes the current thread to pause its execution and wait for another thread to finish. (The current thread goes from running to Waiting, and then to Runnable).

Why is it necessary to synchronize on the same lock when reading and writing the state of an object? (2 reasons)

It is necessary for two reasons. Mutal exclusion and visibility. Mutual Exclusion: A thread that's reading a value holding the wrong lock won't block if another thread is currently modifying that value holding another lock. Visibility: A thread is not guaranteed to see the changes.

How do you compare the barrier synchronizer with real life?

It is similar to the rendezvous protocol followed by family members: everybody agrees on meeting at a certain place and when all members get there, they decide what to do next.

When is an InterruptedException thrown?

It is thrown when another thread calls Thread.interrupt instance method.

What is the InterruptedException and gives some examples of methods that throw it? (2)

It's a checked exception thrown by methods that can blocked like Thread.sleep, BlockingQueue.put instance method, etc.

What is ThreadLocal?

It's a class that allows us to keep a per-thread value. Thus, if two threads are accessing the same code and using a threadLocal instance they one see each other instance's value.

What is a thread-safe class?

It's a class that maintains its consistency in a concurrent environment.

What is the java monitor pattern?

It's a pattern on which classes encapsulate its public state and use synchronized methods to ensure thread-safety.

What is a barrier?

It's a synchronizer on which all threads need to come together at a barrier point to proceed.

What is ad hoc confinment?

It's a variable that can be accessed by many threads (like a public variable) but is only accessed by one of them.

What is a synchronizer?

It's an object that coordinates the flow of threads based on its state.

What is an escape object?

It's an object that has been published unintentionally. So other threads may see the object in an inconsistent state or mutate it unsafely (without preserving its invariants).

What is an immutable Object?

It's an object whose state cannot be modified after construction.

What are some type of synchronizers in java.util.concurrent? (5)

Latches, semaphores, barriers, blocking queues, future task.

What are some implementations of the BlockingQueue interface? (4)

LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue, SynchronousQueue

What is Stack confinement?

Local variables that aren't published to another thread.

What is the difference between locking (synchronizing) and volatile?

Locking can ensure both atomicity and visibility, while volatile can only ensure visibility.

What are some common mistakes when using synchronized for enabling atomicity?

Locking on the wrong lock Synchronizing only when mutating state (instead of both reading and writting access to variables).

How can you defensively copy a collection?

Make a new instance of the collection and if elements are mutable make a copy of each one.

What are the different ways to add functionality to existing thread-safe classes? (4)

Modify the class directly Extend the class Client Locking Composition

How does synchronization work?

On a concurrent environment, If several threads mutate the same object at the same time without any order unexpected things may happen and data can be corrupted. Synchronization is a mechanism to fix that problem by using the idea of locks. Every object has a lock, entering a synchronized block means acquiring the lock and exit it means releasing the lock. If a thread has one object's lock, that means it has exclusive access to that object and other threads have to wait until the thread releases the lock.

When does work stealing work the best?

On scenarios were producers are also consumers, in other words, when producing a unit of work is likely to produce more work.

How do you compare the producer consumer pattern and the work stealing pattern?

On the producer-consumer design pattern, there is one single work queue for both producers and consumers, on the other hand, on the work stealing pattern, every consumer has its own queue and when the consumer exhausts its work it will steal from another consumer's queue (from the tail to avoid contigency).

How can you stop a running Thread? (2)

One thread cannot cause another thread to stop. But there are cooperative mechanisms to request a thread to stop or pause its execution. For example: using status flags, or calling Thread.interrupt instance method on a thread that is responsive to interruption.

What are some possible drawbacks of defensive copying? (2)

Performance, no uptodate data.

What does atomic mean?

Similar to the transaction concept, atomic is a compound action which steps are indivisible (all the steps need to run until completion).

What is the primary advantage and disadvantage of the Java Monitor Pattern?

Simplicity and performance respectevely.

How can you start the computation of a FutureTask (in other words run the runnable or the callable it wraps)? (2)

Since the FutureTask is itself a Runnable there are two ways: 1) Passing the task to a thread instance and starting the thread 2) Passing the task to the execute method of an executorService.

Mention one typical used for the volatile keyword?

Status flag for completion or interruption.

What is one disadvantage of using ad-hoc thread confinement?

That this kind of confinement is not guaranteed by the language itself but by the programmer. Therefore it is a fragile strategy and should be documented so that maintainers of the code are aware of it.

What are the risks of accessing a 64 bit long variable without syncrhonization?

The JVM stores 64-bit long as two separate 32-bit integers. In the absence of synchronization threads may see the 32-bit integer that one thread wrote and the 32-bit integer of another thread.

Which object are you locking on when synchronizing a static method?

The object that represents that class (ClassName.class)

What object is used for locking by convention in the Java Monitor Pattern?

The object's intrinsic lock. However locking on another object is totally fine when using it consistently.

What is the synchronized keyword used for?

The synchronized keyword allow can be applied to blocks of code and methods to ensure both atomicity and visibility. A synchronized block or method can only be accessed by one thread at a time.

What is the purpose of using wait, notify or notifyAll?

These methods allow threads to communicate status changes.

What is one of the simplest ways to achieve thread safety?

Thread confinment

What is client side locking?

Using a helper class that will provide new synchronized methods, locking on the same lock another class is using.

How can you ensure atomicity?

Using synchronized Using atomic data types like AtomicLong

What is a simple way to make basic collections like ArrayList and HashMap thread-safe?

Using the helper methods: Collections.synchronizedXXX(collectionXXX)

What is one way to preserve thread safety when porting a single-threaded program that uses global variables to multithread?

Using threadLocal, however, both global variables and thread local should be used sparingly since they can promote coupling.

Give an example of a Java library class that uses the Monitor Pattern? (2)

Vector and Hashtable.

What is the volatile keyword?

Volatile keyword is a way of ensuring visibility without blocking. Once a thread modifies a variable, subsequent reads to that variable will be visible for the other threads.

What are the different states the Runnable or Callable wrapped in a FutureTask can be in? (3)

Waiting to Run, Running, Completed.

What should be one aim when synchronizing?

We should aim to synchronize the shortest code path without abusing granularity or simplicity.

When is delegation not sufficient to ensure thread safety in a class?

When atomicity is a requirement and the compound action cannot be delegated to any of the instance variables.

In which case you shouldn't use volatile? (Give 2 examples)

When atomicity is a requirement. For example: 1) When writing to the volatile variable depends on its previous state. 2) When the volatile variable participates in invariants with other variables.

What are latches useful for? Give some examples (3)

When some activities depend on other activities readiness to proceed. For example: 1) Await until some resource has been initialized. 2) Await until all the parties involve in an activity are ready (like all the player on a multiplayer game) 3) Ensure a service does not run until other services it depends on has started.

From the perspective of preserving a class invariants, in which case is it suitable to declare or use a volatile variable?

When the volatile variable does not participate on invariants including other variables.

Can you have synchronized static methods?

Yes. Locking will be on the class level. There is one lock per class.

How can you respond to interruption when you call a blocking method that can throw InterruptedException? (2)

You have to choices: 1) Rethrow it 2) Catch it an restore the interrupted status by calling Thread.currentThread.interrupt().

How can you use a non-threadsafe object in a multithreaded program? (2)

You may confine the object to a single thread or use synchronization.

What are the method notify and notifyAll used for?

notify awake one of the waiting threads (go from Waiting to Runnable). notifyAll, awake all of the waiting threads.

What are some mechanisms for ensuring visibility? (2)

using synchronized or volatile.


Conjuntos de estudio relacionados

Marketing Channels: Delivering Customer Value

View Set

Cram 21: Total War on the Homefront

View Set

El Mundo Conectado + Internado 5-5

View Set