thread-safety interview questions
Top thread-safety frequently asked interview questions
If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method?
Example:
class X {
private int a;
private int b;
public synchronized void addA(){
a++;
}
public synchronized void addB(){
b++;
}
}
Can 2 threads access the same instance of class X performing x.addA(
) and x.addB()
at the same time?
Source: (StackOverflow)
I saw different binaries for PHP, like non thread or thread safe? What does this mean? What is the difference between these packages?
Source: (StackOverflow)
I see that for using objects which are not thread safe we wrap the code with a lock like this:
private static readonly Object obj = new Object();
lock (obj)
{
// thread unsafe code
}
So what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?
What is the performance impact because of using locks?
Source: (StackOverflow)
Please tell with a code example why is SimpleDateFormat not threadsafe. What is the problem in this class?
Is The problem with format function of SimpleDateFormat?
Please give a code which demonstrates this fault in class.
FastDateFormat is threadsafe. Why?
what is the difference b/w the SimpleDateFormat and FastDateFormat?
Please explain with a code which demonstrates this issue?
Source: (StackOverflow)
I have become painfully aware of just how often one needs to write the following code pattern in event-driven GUI code, where
private void DoGUISwitch() {
// cruisin for a bruisin' through exception city
object1.Visible = true;
object2.Visible = false;
}
becomes:
private void DoGUISwitch() {
if (object1.InvokeRequired) {
object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
} else {
object1.Visible = true;
object2.Visible = false;
}
}
This is an awkward pattern in C#, both to remember, and to type. Has anyone come up with some sort of shortcut or construct that automates this to a degree? It'd be cool if there was a way to attach a function to objects that does this check without having to go through all this extra work, like a object1.InvokeIfNecessary.visible = true
type shortcut.
Previous answers have discussed the impracticality of just calling Invoke() every time, and even then the Invoke() syntax is both inefficient and still awkward to deal with.
So, has anyone figured out any shortcuts?
Source: (StackOverflow)
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur. Below is the code.
This is a WCF server in a Windows service. The method NotifySubscribers is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day).
When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine.
Do you see a problem with this code? Do I need to make the dictionary thread-safe?
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class SubscriptionServer : ISubscriptionServer
{
private static IDictionary<Guid, Subscriber> subscribers;
public SubscriptionServer()
{
subscribers = new Dictionary<Guid, Subscriber>();
}
public void NotifySubscribers(DataRecord sr)
{
foreach(Subscriber s in subscribers.Values)
{
try
{
s.Callback.SignalData(sr);
}
catch (Exception e)
{
DCS.WriteToApplicationLog(e.Message,
System.Diagnostics.EventLogEntryType.Error);
UnsubscribeEvent(s.ClientId);
}
}
}
public Guid SubscribeEvent(string clientDescription)
{
Subscriber subscriber = new Subscriber();
subscriber.Callback = OperationContext.Current.
GetCallbackChannel<IDCSCallback>();
subscribers.Add(subscriber.ClientId, subscriber);
return subscriber.ClientId;
}
public void UnsubscribeEvent(Guid clientId)
{
try
{
subscribers.Remove(clientId);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Unsubscribe Error " +
e.Message);
}
}
}
Source: (StackOverflow)
I know that compound operations such as i++
are not thread safe as they involve multiple operations.
But is checking the reference with itself a thread safe operation?
a != a //is this thread-safe
I tried to program this and use multiple threads but it didn't fail. I guess I could not simulate race on my machine.
EDIT:
public class TestThreadSafety {
private Object a = new Object();
public static void main(String[] args) {
final TestThreadSafety instance = new TestThreadSafety();
Thread testingReferenceThread = new Thread(new Runnable() {
@Override
public void run() {
long countOfIterations = 0L;
while(true){
boolean flag = instance.a != instance.a;
if(flag)
System.out.println(countOfIterations + ":" + flag);
countOfIterations++;
}
}
});
Thread updatingReferenceThread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
instance.a = new Object();
}
}
});
testingReferenceThread.start();
updatingReferenceThread.start();
}
}
This is the program that I am using to test the thread-safety.
Weird behavior
As my program starts between some iterations I get the output flag value, which means that the reference !=
check fails on the same reference. BUT after some iterations the output becomes constant value false
and then executing the program for a long long time does not generate a single true
output.
As the output suggests after some n (not fixed) iterations the output seems to be constant value and does not change.
Output:
For some iterations:
1494:true
1495:true
1496:true
19970:true
19972:true
19974:true
//after this there is not a single instance when the condition becomes true
Source: (StackOverflow)
I know this is an often asked question, but as there are so many variants, I'd like to re-state it, and hopefully have an answer reflecting the current state. Something like
Logger& g_logger() {
static Logger lg;
return lg;
}
Is the constructor of variable lg guaranteed to run only once?
I know from previous answers that in C++03, this is not; in C++0x draft, this is enforced. But I'd like a clearer answer to
- In C++11 standard (not draft), is the thread-safe initialization behavior finalized?
- If the above is yes, in current latest releases of popular compilers, namely gcc 4.7, vc 2011 and clang 3.0, are they properly implemented?
Source: (StackOverflow)
I was wondering if you have a static method that is 'not' synchronised, but does 'not' modify any static variables is it thread-safe? What about if the method creates local variables inside it? For example, is the following code thread-safe?
public static String[] makeStringArray( String a, String b ){
return new String[]{ a, b };
}
So if I have two threads calling ths method continously and concurrently, one with dogs (say "great dane" and "bull dog") and the other with cats (say "persian" and "siamese") will I ever get cats and dogs in the same array? Or will the cats and dogs never be inside the same invocation of the method at the same time?
Source: (StackOverflow)
I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object:
public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
private readonly object syncRoot = new object();
private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();
public object SyncRoot
{
get { return syncRoot; }
}
public void Add(TKey key, TValue value)
{
lock (syncRoot)
{
d.Add(key, value);
}
}
// more IDictionary members...
}
I then lock on this SyncRoot object throughout my consumers (multiple threads):
Example:
lock (m_MySharedDictionary.SyncRoot)
{
m_MySharedDictionary.Add(...);
}
I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?
Source: (StackOverflow)
Most of the times, the definition of reentrance is quoted from Wikipedia:
A computer program or routine is
described as reentrant if it can be
safely called again before its
previous invocation has been completed
(i.e it can be safely executed
concurrently). To be reentrant, a
computer program or routine:
- Must hold no static (or global)
non-constant data.
- Must not return the address to
static (or global) non-constant
data.
- Must work only on the data provided
to it by the caller.
- Must not rely on locks to singleton
resources.
- Must not modify its own code (unless
executing in its own unique thread
storage)
- Must not call non-reentrant computer
programs or routines.
How is safely defined?
If a program can be safely executed concurrently, does it always mean that it is reentrant?
What exactly is the common thread between the six points mentioned that I should keep in mind while checking my code for reentrant capabilities?
Also,
- Are all recursive functions reentrant?
- Are all thread-safe functions reentrant?
- Are all recursive and thread-safe functions reentrant?
While writing this question, one thing comes to mind:
Are the terms like reentrance and thread safety absolute at all i.e. do they have fixed concrete definations? For, if they are not, this question is not very meaningful.
Source: (StackOverflow)
I hear that const
means thread-safe in C++11. Is that true?
Does that mean const
is now the equivalent of Java's synchronized
?
Are they running out of keywords?
Source: (StackOverflow)
class ThreadSafeClass extends Thread
{
private static int count = 0;
public synchronized static void increment()
{
count++;
}
public synchronized void decrement()
{
count--;
}
}
Can anyone explain why above class is not thread safe?
Source: (StackOverflow)
Is it valid to share one instance of the Random
class between multiple threads? And to call nextInt(int)
from multiple threads in particular?
Source: (StackOverflow)