The Following Code Snippet Changes the Counter Class to Maintain Individual Counting as in each user Counter will be Incremented Starting from 1

The following code snippet changes the Counter class to maintain individual counting as in each user counter will be incremented starting from 1. So, the Counter will no longer be the shared resource. The CountingTask class is also modified to loop through each user 2 times as shown below. Is there anything wrong with the … Read more

How will you Fix the Above Racing Issue

This can be fixed a number of ways. Option 1: Method level synchronization. This is the simplest. As you can see, the increment() method is synchronized, so that the other threads must wait for the thread that already has the lock to execute that method. import java.util.HashMap; import java.util.Map;   public class Counter {   //shared … Read more

Explain how you would get Thread-Safety Issues due to Non-Atomic Operations with a Code Example

The code snippets below demonstrates non-atomic operations producing incorrect results with code. The program below uses a shared Counter object, that is shared between three concurrent users (i.e. three threads). The Counter object is responsible for incrementing the counter. Firstly, the Counter class. The counted values are stored in a HashMap by name (i.e. thread name) as the key for … Read more

Can you have a True Singleton Class in Java? How would you Write a Thread-Safe Singleton Class

A singleton class is something for which only one instance exists per class loader. Single instance for a wholeapplication cannot be guaranteed. That is just definition of what is singleton. The one that is  popular with the interviewers is writing a thread-safe singleton class. For example, the following singleton class is not thread-safe because before a thread creates … Read more

Can you give some Examples of Thread Racing Conditions you had Experienced

Declaring variables in JSP pages are not thread-safe. The declared variables in JSP pages end-up as instance variables in the converted Servlets. <%! Calendar c = Calendar.getInstance(); %> Decalring instance variables in Servlets is not thread safe, as Servlets are inherently multi-threaded and gets accessed by multiple-threads. Same is true for the Actionclasses in the … Read more