Which One Of The Following Directives Communicates Buffer And Thread Safety Information

Which of the following options is thread-safe?

What is thread safety ? thread-safety or thread-safe code in Java refers to code that can safely be utilized or shared in concurrent or multi-threading environment and they will behave as expected. Thread-safety is one of the risks introduced by using threads in Java and I have seen java programmers and developers struggling to write thread-safe code or just understanding what is thread-safe code and what is not? Before you learn how to write a thread-safe code you need to understand what is thread-safety and there is no better way to that than looking at a non-thread-safe code.

  1. So, let’s see an example of the potential, not thread-safe code, and learn how to fix that.
  2. Here is an example of a non-thread-safe code, look at the code, and find out why this code is not thread-safe ? Example 1 public class NumberCounter public int getCountAtomically() } The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.

If multiple thread call getCount() approximately same time each of these three operations may coincide or overlap with each other for example while thread 1 is updating value, thread 2 reads and still gets old value, which eventually let thread 2 override thread 1 increment and one count is lost because multiple threads called it concurrently.

Example 2 public class BasicObservableClass private Set mObservers; public void registerObserver(Observer observer) if (mObservers == null) mObservers.add(observer); } public void unregisterObserver(Observer observer) } private void notifyObservers() for (Observer observer : mObservers) } } In the most general case of multi-threaded environment we shall assume that all methods will be called on random threads at random times.

The implementation we used for a single-threaded environment is not safe anymore. It is not hard to imagine a flow when two distinct threads attempt to register new Observers at the same time, and end up leaving our system screwed up. One such flow could be (there are many other flows which could break non-thread-safe implementation):

Thread A invokes registerObserver(Observer) Thread A executes mObservers == null check and proceeds to instantiation of a new setbefore Thread A got a chance to create a new set, OS suspended it and resumed execution of Thread BThread B executes steps 1 and 2 abovesince Thread A hasn’t instantiated the set yet, Thread B instantiates a new set and stores a reference to it in mObservers Thread B adds an observer to the newly created setat some point OS resumes execution of Thread A (which was suspended right before instantiation of a new set)Thread A instantiates a new set and overrides the reference in mObservers Thread A adds an observer to the newly created set

Despite the fact that both calls to registerObserver(Observer) completed successfully, the end result is that only one observer will be notified when notifyObservers() called. It is important to understand that any of the observers could end up being “ignored”, or both observers could be registered successfully – the outcome depends on the scheduling of threads by OS which we can’t control.

  1. This non-determinism is what makes multi-threading bugs very hard to track and resolve.
  2. There are multiple ways to make this code thread-safe in Java: 1) Use the synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes the possibility of coinciding or interleaving.2) use Atomic Integer, which makes this ++ operation atomic and since atomic operations are thread-safe and saves the cost of external synchronization.

Here is a thread-safe version of NumberCounter class in Java: public class NumberCounter public int getCountAtomically() } Here are some points worth remembering to write thread-safe code in Java, this knowledge also helps you to avoid some serious concurrency issues in Java-like race condition or deadlock in Java: 1) Immutable objects are by default thread-safe because their state can not be modified once created.

Which of the following methods can be used to ensure thread safety of a code which is to be executed on a typical Java 8 Runtime Environment?

Java synchronized – Synchronization is the tool using which we can achieve thread-safety, JVM guarantees that synchronized code will be executed by only one thread at a time. java keyword synchronized is used to create synchronized code and internally it uses locks on Object or Class to make sure only one thread is executing the synchronized code.

Java synchronization works on locking and unlocking of the resource before any thread enters into synchronized code, it has to acquire the lock on the Object and when code execution ends, it unlocks the resource that can be locked by other threads. In the meantime, other threads are in wait state to lock the synchronized resource. We can use synchronized keyword in two ways, one is to make a complete method synchronized and another way is to create synchronized block. When a method is synchronized, it locks the Object, if method is static it locks the Class, so it’s always best practice to use synchronized block to lock the only sections of method that needs synchronization. While creating a synchronized block, we need to provide the resource on which lock will be acquired, it can be XYZ.class or any Object field of the class. synchronized(this) will lock the Object before entering into the synchronized block. You should use the lowest level of locking, for example, if there are multiple synchronized block in a class and one of them is locking the Object, then other synchronized blocks will also be not available for execution by other threads. When we lock an Object, it acquires a lock on all the fields of the Object. Java Synchronization provides data integrity on the cost of performance, so it should be used only when it’s absolutely necessary. Java Synchronization works only in the same JVM, so if you need to lock some resource in multiple JVM environment, it will not work and you might have to look after some global locking mechanism. Java Synchronization could result in deadlocks, check this post about deadlock in java and how to avoid them, Java synchronized keyword cannot be used for constructors and variables. It is preferable to create a dummy private Object to use for the synchronized block so that it’s reference can’t be changed by any other code. For example, if you have a setter method for Object on which you are synchronizing, it’s reference can be changed by some other code leads to the parallel execution of the synchronized block. We should not use any object that is maintained in a constant pool, for example String should not be used for synchronization because if any other code is also locking on same String, it will try to acquire lock on the same reference object from String pool and even though both the codes are unrelated, they will lock each other.

Here are the code changes we need to do in the above program to make it thread-safe. //dummy object variable for synchronization private Object mutex=new Object();, //using synchronized block to read, increment and update count value synchronously synchronized (mutex) Let’s see some synchronization examples and what can we learn from them.

public class MyObject } // Hackers code MyObject myObject = new MyObject(); synchronized (myObject) } Notice that hacker’s code is trying to lock the myObject instance and once it gets the lock, it’s never releasing it causing doSomething() method to block on waiting for the lock, this will cause the system to go on deadlock and cause Denial of Service (DoS).

You might be interested:  How To Talk To Your Child About Body Safety

public class MyObject } } //untrusted code MyObject myObject = new MyObject(); //change the lock Object reference myObject.lock = new Object(); Notice that lock Object is public and by changing its reference, we can execute synchronized block parallel in multiple threads.

  1. A similar case is true if you have private Object but have a setter method to change its reference.
  2. Public class MyObject } // hackers code synchronized (MyObject.class) } Notice that hacker code is getting a lock on the class monitor and not releasing it, it will cause deadlock and DoS in the system.

Here is another example where multiple threads are working on the same array of Strings and once processed, appending thread name to the array value. package com.journaldev.threads; import java.util.Arrays; public class SyncronizedMethod ; HashMapProcessor hmp = new HashMapProcessor(arr); Thread t1=new Thread(hmp, “t1”); Thread t2=new Thread(hmp, “t2”); Thread t3=new Thread(hmp, “t3”); long start = System.currentTimeMillis(); //start all the threads t1.start();t2.start();t3.start(); //wait for threads to finish t1.join();t2.join();t3.join(); System.out.println(“Time taken= “+(System.currentTimeMillis()-start)); //check the shared variable value now System.out.println(Arrays.asList(hmp.getMap())); } } class HashMapProcessor implements Runnable public String getMap() @Override public void run() private void processArr(String name) } private void addThreadName(int i, String name) private void processSomething(int index) catch (InterruptedException e) } } Here is the output when I run the above program.

Time taken= 15005 The String array values are corrupted because of shared data and no synchronization. Here is how we can change addThreadName() method to make our program thread-safe. private Object lock = new Object(); private void addThreadName(int i, String name) } After this change, our program works fine and here is the correct output of the program.

Time taken= 15004 That’s all for thread safety in java, I hope you learned about thread-safe programming and using synchronized keyword.

Which of the following implementations of collection are thread-safe?

Which collection classes are thread-safe in Java A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Why StringBuffer is thread-safe?

Difference between StringBuffer and StringBuilder

Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5. A list of differences between StringBuffer and StringBuilder is given below:

No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can’t call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

Which data structure is thread-safe?

How to design thread safe data structures? – One way to design thread safe data structures is to use immutable data structures, which are data structures that cannot be modified after they are created. Immutable data structures are inherently thread safe, because they do not allow any concurrent modifications that can cause inconsistency or corruption.

For example, Ruby provides immutable data structures such as strings, symbols, numbers, and frozen arrays and hashes. Immutable data structures can be used to store constants, configuration, or other static data that do not change during the program execution. Another way to design thread safe data structures is to use concurrency abstractions, which are data structures that provide high-level methods and guarantees for concurrent access and modification.

Concurrency abstractions can simplify the complexity and reduce the errors of managing thread safety manually. For example, Ruby provides concurrency abstractions such as Queue, SizedQueue, ThreadGroup, and Mutex, which can be used to implement producer-consumer patterns, thread pools, or mutual exclusion locks.

How can you communicate from one thread to another?

Inter-thread Communication – There are three ways for threads to communicate with each other. The first is through commonly shared data. All the threads in the same program share the same memory space. If an object is accessible to various threads then these threads share access to that object’s data member and thus communicate each other.

  1. The second way for threads to communicate is by using thread control methods.
  2. There are such three methods by which threads communicate for each other : suspend ( ) : A thread can suspend itself and wait till other thread resume it.
  3. Resume ( ) : A thread can wake up other waiting thread (which is waiting using suspend() ) through its resume() method and then can run concurrently.

join ( ) :This method can be used for the caller thread to wait for the completion of called thread. The third way for threads to communicate is the use of three methods; wait(), notify(), and notifyAll(); these are defined in class Object of package java.lang.

Actually these three methods provide an elegant inter-process communication mechanism to take care the deadlock situation in Java. As there is multi-threading in program, deadlock may occur when a thread holding the key to monitor is suspended or waiting for another thread’s completion. If the other thread is waiting for needs to get into the same monitor, both threads will be waiting for ever.

The uses of these three methods are briefed as below : wait ( ) :This method tells the calling thread to give up the monitor and make the calling thread wait until either a time out occurs or another thread call the same thread’s notify() or notifyAll() method.

How to safely communicate between multiple threads in the program?

Python | Communicating Between Threads | Set-1 – GeeksforGeeks

    • Improve Article
    • Save Article
    • Like Article

    Given multiple threads in the program and one wants to safely communicate or exchange data between them. Perhaps the safest way to send data from one thread to another is to use a Queue from the queue library. To do this, create a Queue instance that is shared by the threads.

    1. from queue import Queue
    2. from threading import Thread
    3. def producer(out_q):
    4. while True :


    • out_q.put(data)
    • def consumer(in_q):
    • while True :
    • data = in_q.get()


    1. q = Queue()
    2. t1 = Thread(target = consumer, args = (q, ))
    3. t2 = Thread(target = producer, args = (q, ))
    4. t1.start()
    5. t2.start()

    Queue instances already have all of the required locking, so they can be safely shared by as many threads as per requirement. When using queues, it can be somewhat tricky to coordinate the shutdown of the producer and consumer. A common solution to this problem is to rely on a special sentinel value, which when placed in the queue, causes consumers to terminate as shown in the code below: Code #2 :

    • from queue import Queue
    • from threading import Thread
    • _sentinel = object ()
    • def producer(out_q):
    • while running:


    1. out_q.put(data)
    2. out_q.put(_sentinel)
    3. def consumer(in_q):
    4. while True :
    5. data = in_q.get()
    6. if data is _sentinel:
    7. in_q.put(_sentinel)
    8. break


    A subtle feature of the code above is that the consumer, upon receiving the special sentinel value, immediately places it back onto the queue. This propagates the sentinel to other consumers threads that might be listening on the same queue—thus shutting them all down one after the other.

    • import heapq
    • import threading
    • class PriorityQueue:
    • def _init_( self ):
    • self,_queue =
    • self,_count = 0

    self,_cv = threading.Condition() def put( self, item, priority): with self,_cv: heapq.heappush( self,_queue, ( – priority, self,_count, item)) self,_count + = 1 self,_cv.notify()

    1. def get( self ):
    2. with self,_cv:
    3. while len ( self,_queue) = = 0 :

    self,_cv.wait() return heapq.heappop( self,_queue)

    Thread communication with a queue is a one-way and non-deterministic process. In general, there is no way to know when the receiving thread has actually received a message and worked on it. However, Queue objects do provide some basic completion features, as illustrated by the task_done() and join() methods in the example given below – Code #4 :

    • from queue import Queue
    • from threading import Thread
    • def producer(out_q):
    • while running:


    1. out_q.put(data)
    2. def consumer(in_q):
    3. while True :
    4. data = in_q.get()


    • in_q.task_done()
    • q = Queue()
    • t1 = Thread(target = consumer, args = (q, ))
    • t2 = Thread(target = producer, args = (q, ))
    • t1.start()
    • t2.start()
    • q.join()


  • Last Updated : 12 Jun, 2019
  • Like Article
  • Save Article
  • What strategies we can use to achieve thread safety?

    So, another common approach that we can use for achieving thread-safety is implementing synchronized methods. Simply put, only one thread can access a synchronized method at a time, while blocking access to this method from other threads.

    What is a safety rule on thread?

    Thread Safety – Multithreaded Programming Guide Thread safety is the avoidance of data races. Data races occur when data are set to either correct or incorrect values, depending upon the order in which multiple threads access and modify the data. When no sharing is intended, give each thread a private copy of the data.

    Unsafe Thread safe, Serializable Thread safe, MT-Safe

    An unsafe procedure can be made thread safe and able to be serialized by surrounding the procedure with statements to lock and unlock a mutex. shows three simplified implementations of fputs(), initially thread unsafe. Next is a serializable version of this routine with a single mutex protecting the procedure from concurrent execution problems.

    • Actually, the single mutex is stronger synchronization than is usually necessary.
    • When two threads are sending output to different files by using fputs(), one thread need not wait for the other thread.
    • The threads need synchronization only when sharing an output file.
    • The last version is MT-safe.
    • This version uses one lock for each file, allowing two threads to print to different files at the same time.

    So, a routine is MT-safe when the routine is thread safe, and the routine’s execution does not negatively affect performance. Example 7-1 Degrees of Thread Safety /* not thread-safe */ fputs(const char *s, FILE *stream) /* serializable */ fputs(const char *s, FILE *stream) /* MT-Safe */ mutex_t m; fputs(const char *s, FILE *stream) : Thread Safety – Multithreaded Programming Guide

    How to implement thread-safe in C#?

    This page describes how to develop a thread-sage cache using the C# lock statement and the ConcurrentDictionary class. A method is thread-safe if multiple threads can call it without breaking the functionality. Achieving thread safety is a complex task, so general-purpose classes are usually not thread-safe. The most common way to achieve thread safety is to lock the resource for exclusive use by a single thread at any given time. You need to develop a web application where multiple users can simultaneously view the same file. The web application uses GroupDocs.Viewer on the server side. You have to ensure that multiple threads can safely read and write to the cache. In GroupDocs.Viewer, you can use caching to improve the performance if the same document is processed multiple times ( read more about caching here,) The FileCache class is an implementation of the ICache interface that uses a local disk to store the cache files. The FileCache is not thread safe, so you need to make it so. The FileCache class uses a local disk to read and write output files. You need to implement thread safe reading and writing to disk. To do this, use the list to store the key or the file ID and associated object you need to lock. The simplest way is to use the ConcurrentDictionary class of the,NET Framework 4.0, The ConcurrentDictionary is a thread safe implementation of a dictionary of key-value pairs. Implement the ThreadSafeCache class that wraps around not thread safe class that implements the ICache interface. C# internal class ThreadSafeCache : ICache public void Set ( string key, object value ) } public bool TryGetValue < TEntry >( string key, out TEntry value ) } public IEnumerable < string > GetKeys ( string filter ) } } All the ThreadSafeCache class methods use locks to make calls thread safe. The ConcurrentDictionaryKeyLockerStore class uses ConcurrentDictionary to create the locker object or to retrieve it if it already exists. It also creates a unique key that identifies a cached file. C# interface IKeyLockerStore class ConcurrentDictionaryKeyLockerStore : IKeyLockerStore public object GetLockerFor ( string key ) private string GetUniqueKey ( string key ) _ ” ; } } C# using System.Collections.Concurrent ; using System.Collections.Generic ; using System.IO ; using GroupDocs.Viewer ; using GroupDocs.Viewer.Caching ; using GroupDocs.Viewer.Interfaces ; using GroupDocs.Viewer.Options ; namespace ThreadSaveCacheExample } } class ThreadSafeCache : ICache public void Set ( string key, object value ) } public bool TryGetValue < TEntry >( string key, out TEntry value ) } public IEnumerable < string > GetKeys ( string filter ) } } interface IKeyLockerStore class ConcurrentDictionaryKeyLockerStore : IKeyLockerStore public object GetLockerFor ( string key ) private string GetUniqueKey ( string key ) _ ” ; } } class MemoryPageStreamFactory : IPageStreamFactory public Stream CreatePageStream ( int pageNumber ) public void ReleasePageStream ( int pageNumber, Stream pageStream ) } } We value your opinion. Your feedback will help us improve our documentation.

    Which class is thread-safe in multiple threads Cannot access?

    Conclusion –

    StringBuffer in java is used for storing mutable sequences that increase their efficiency. The object of StringBuffer in java is thread safe multiple threads cannot access the StringBuffer particular object simultaneously. StringBuffer is fastest than the String class due to the mutable property of the StringBuffer class. The default capacity of the StringBuffer in java is 16 bytes. StringBuffer is mostly used when we perform several dynamic addition operations. We cannot use the String class because it will cause a lot of memory waste due to the immutable property of the String class.

    Which class is thread-safe multiple threads Cannot access it simultaneously so it is safe and will result in an order?

    The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed. Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

    Is StringBuffer or StringBuilder thread-safe?

    StringBuffer is thread-safe and synchronized whereas StringBuilder is not.

    When to use StringBuffer vs StringBuilder?

    Difference between String buffer and String builder in Java String buffer and StringBuilder both are mutable classes which can be used to do operation on string objects such as reverse of string, concating string and etc. We can modify string without creating a new object of the string.

    Sr. No. Key String Buffer String Builder
    1 Basic StringBuffer was introduced with the initial release of Java It was introduced in Java 5
    2 Synchronized It is synchronized It is not synchronized
    3 Performance It is thread-safe. So, multiple threads can’t access at the same time, therefore, it is slow. It is not thread-safe hence faster than String Buffer
    4 Mutable It is mutable. We can modify string without creating an object It is also mutable
    5 Storage Heap Heap

    Is Static StringBuffer thread-safe?

    StringBuffer is synchronized and therefore thread-safe. StringBuilder is compatible with StringBuffer API but with no guarantee of synchronization.

    Is HashMap thread-safe?

      Differences between HashMap and HashTable in Java

      • Improve Article
      • Save Article
      • Like Article
      1. Improve Article
      2. Save Article
      3. Like Article

      and store key and value pairs in a hash table. When using a Hashtable or HashMap, we specify an object that is used as a key and the value that you want to be linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. Now let us discuss with the help of an example. Hashmap vs Hashtable

      • HashMap is non-synchronized. It is not thread-safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
      • HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
      • HashMap is generally preferred over HashTable if thread synchronization is not needed.
      S. No. Hashmap Hashtable
      1. No method is synchronized. Every method is synchronized.
      2. Multiple threads can operate simultaneously and hence hashmap’s object is not thread-safe. At a time only one thread is allowed to operate the Hashtable’s object. Hence it is thread-safe.
      3. Threads are not required to wait and hence relatively performance is high. It increases the waiting time of the thread and hence performance is low.
      4. Null is allowed for both key and value. Null is not allowed for both key and value. Otherwise, we will get a null pointer exception.
      5. It is introduced in the 1.2 version. It is introduced in the 1.0 version.
      6. It is non-legacy. It is a legacy.

      Now you must be wondering why HashTable doesn’t allow null and HashMap do ? The answer is simple. In order to successfully store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode method and the equals method. Since null is not an object, it can’t implement these methods.

      import java.util.*; import java.lang.*; import java.io.*;

      • class Ideone
      • HashMap hm= new HashMap ();
      • hm.put( 100, “Amit” );
      • hm.put( 104, “Amit” );
      • hm.put( 101, “Vijay” );
      • hm.put( 102, “Rahul” );
      • System.out.println( “-Hash map-” ); for (Map.Entry m:hm.entrySet())

      • }
      • }

      Output -Hash table- 103 Rahul 102 Ravi 101 Vijay -Hash map- 100 Amit 101 Vijay 102 Rahul 104 Amit This article is compiled by Aditya Goel, Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

      1. Last Updated : 23 Jan, 2022
      2. Like Article
      3. Save Article

      : Differences between HashMap and HashTable in Java

      Which of the following collection is not thread-safe?

      3. Synchronized Wrappers – So far we’ve understood that the basic collection implementations are not thread-safe in order to provide maximum performance in single-threaded applications. What if we have to use collections in multi-threaded context? Of course we should not use non-thread-safe collections in concurrent context, as doing so may lead to undesired behaviors and inconsistent results.

      • We can use synchronized blocks manually to safeguard our code, however it’s always wise to use thread-safe collections instead of writing synchronization code manually.
      • You already know that, the Java Collections Framework provides factory methods for creating thread-safe collections.
      • These methods are in the following form: Collections.synchronizedXXX(collection) These factory methods wrap the specified collection and return a thread-safe implementation.

      Here, XXX can be Collection, List, Map, Set, SortedMap and SortedSet implementations. For example, the following code creates a thread-safe list collection: List safeList = Collections.synchronizedList(new ArrayList ()); If we have an existing non-thread-safe collection, we can wrap it in a thread-safe collection like this: Map unsafeMap = new HashMap (); Map safeMap = Collections.synchronizedMap(unsafeMap); You see, these factory methods wrap the specified collection in an implementation having same interfaces as the wrapped collection but all the methods are synchronized to provide thread-safety, hence the term ‘ synchronized wrappers ‘.

      Actually, the synchronized collection delegate all work to the wrapped collection. NOTE: When using the iterator of a synchronized collection, we should use synchronized block to safeguard the iteration code because the iterator itself is not thread-safe. Consider the following code: List safeList = Collections.synchronizedList(new ArrayList ()); // adds some elements to the list Iterator iterator = safeList.iterator(); while (iterator.hasNext()) Although the safeList is thread-safe, its iterator is not, so we should manually add synchronized block like this: synchronized (safeList) } Also note that the iterators of the synchronized collections are fail-fast.

      Although synchronized wrappers can be safely used in multi-threaded applications, they have drawbacks as explained in the next section.4. Concurrent Collections A drawback of synchronized collections is that their synchronization mechanism uses the collection object itself as the lock object.

      1. That means when a thread is iterating over elements in a collection, all other collection’s methods block, causing other threads having to wait.
      2. Other threads cannot perform other operations on the collection until the first thread release the lock.
      3. This causes overhead and reduces performance.
      4. That’s why Java 5 (and beyond) introduces concurrent collections that provide much better performance than synchronized wrappers.

      The concurrent collection classes are organized in the java.util.concurrent package. They are categorized into 3 groups based on their thread safety mechanisms. * The first group is copy-on-write collections: this kind of thread-safe collections stores values in an immutable array; any change to the value of the collection results in a new array being created to reflect the new values.

      These collections are designed for situations in which read operations greatly predominate write operations. There are two implementations of this kind: CopyOnWriteArrayList and CopyOnWriteArraySet, Note that copy-on-write collections have snapshot iterators which do not throw ConcurrentModificationException,

      Since these collections are backed by immutable arrays, an iterator can read the values in one of these arrays (but never modify them) without danger of them being changed by another thread. * The second group is Compare-And-Swap or CAS collections: the collections in this group implement thread safety using an algorithm called Compare-And-Swap (CAS) which can be understood like this: To perform calculation and update value of a variable, it makes a local copy of the variable and performs the calculation without getting exclusive access.

      1. When it is ready to update the variable, it compares the variable’s value with its value at the start and, if they are the same, updates it with the new value.
      2. If they are not the same, the variable must have been changed by another thread.
      3. In this situation, the CAS thread can try the whole computation again using the new value, or give up, or continue.

      Collections using CAS include ConcurrentLinkedQueue and ConcurrentSkipListMap, Note that the CAS collections have weakly consistent iterators, which reflect some but not necessarily all of the changes that have been made to their backing collection since they were created.

      1. Weakly consistent iterators do not throw ConcurrentModificationException,
      2. The third group is concurrent collections using a special lock object ( java.util.concurrent.lock.Lock ): This mechanism is more flexible than classical synchronization.
      3. This can be understood as following: A lock has the same basic behavior as classical synchronization but a thread can also acquire it under special conditions: only if the lock is not currently held, or with a timeout, or if the thread is not interrupted.

      Unlike synchronization code, in which an object lock is held while a code block or a method is executed, a Lock is held until its unlock() method is called. Some implementations make use of this mechanism to divide the collection into parts that can be separately locked, giving improved concurrency.

      For example, LinkedBlockingQueue has separate locks for the head and the tail ends of the queue, so that elements can be added and removed in parallel. Other collections using this lock include ConcurrentHashMap and most of the implementations of BlockingQueue, Collections in this group also have weakly consistent iterators and do not throw ConcurrentModificationException,

      Let’s summarize the most important points we’ve learned so far today:

      Most collections in the java.util package are not thread-safe in order to provide maximum performance in single-threaded applications. Vector and Hashtable are the only two legacy collections that are thread-safe. Synchronized collections can be created by using the Collection utility class’ factory methods synchronizedXXX(collection), They are thread-safe but poor at performance. Concurrent collections are improved for thread safety and performance with different synchronization mechanisms: copy-on-write, compare-and-swap and special lock. They are organized in java.util.concurrent package.

      You can learn more about concurrent collections in my Java multi-threading/concurrency tutorials,

      How do I make a collection thread-safe?

      System.Collections and System.Collections.Generic – The collection classes in the System.Collections namespace include ArrayList and Hashtable, These classes provide some thread safety through the Synchronized property, which returns a thread-safe wrapper around the collection.

      The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that’s attempting to access the collection must wait for its turn to take the one lock. This process isn’t scalable and can cause significant performance degradation for large collections. Also, the design isn’t protected from race conditions.

      For more information, see Synchronization in Generic Collections, The collection classes in the System.Collections.Generic namespace include List and Dictionary, These classes provide improved type safety and performance compared to the System.Collections classes.

      Which of the following options is thread-safe in servlet?

      The best overall approach to servlet thread safety is to avoid the SingleThreadModel interface and synchronizing access to the service( ) method. This way, your servlet can handle multiple client requests at the same time.

      Which of the following options is thread-safe in JSP?

      The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP. The following page directive sets the isThreadSafe option to false −

      What is thread-safe methods?

      Improve Article Save Article Like Article Improve Article Save Article Like Article As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results.

      Which of the following options is thread-safe Mcq?

      The gathering categories that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etcetera.