Skip to main content

Questions tagged [thread-safety]

A piece of code is thread-safe if it only manipulates data structures in a way that allows consistent execution of this code by multiple threads. A code may be thread safe, conditionally safe (mutual exclusion required) or unsafe (can only be safely used by one thread).

Filter by
Sorted by
Tagged with
1196 votes
16 answers
1.0m views

Collection was modified; enumeration operation may not execute

I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur. Collection was modified; enumeration operation may not execute Below is the code. This is a ...
cdonner's user avatar
  • 37.4k
949 votes
5 answers
470k views

What is thread safe or non-thread safe in PHP?

I saw different binaries for PHP, like non-thread or thread safe? What does this mean? What is the difference between these packages?
O..'s user avatar
  • 11.2k
650 votes
9 answers
432k views

What does a lock statement do under the hood?

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 ...
NLV's user avatar
  • 21.5k
267 votes
7 answers
108k views

queue.Queue vs. collections.deque

I need a queue which multiple threads can put stuff into, and multiple threads may read from. Python has at least two queue classes, queue.Queue and collections.deque, with the former seemingly using ...
miracle2k's user avatar
  • 31.3k
267 votes
9 answers
184k views

Why is Java's SimpleDateFormat not thread-safe? [duplicate]

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 ...
Vivek Sharma's user avatar
  • 2,677
259 votes
8 answers
112k views

What exactly is a reentrant function?

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 ...
Lazer's user avatar
  • 93.2k
258 votes
3 answers
29k views

Use cases for RxJava schedulers

In RxJava there are 5 different schedulers to choose from: immediate(): Creates and returns a Scheduler that executes work immediately on the current thread. trampoline(): Creates and returns ...
bcorso's user avatar
  • 46.5k
246 votes
2 answers
93k views

Is local static variable initialization thread-safe in C++11? [duplicate]

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() { ...
Ralph Zhang's user avatar
  • 5,171
230 votes
11 answers
235k views

Java synchronized method lock on object, or method?

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 ...
wuntee's user avatar
  • 12.4k
223 votes
9 answers
165k views

Concurrent HashSet<T> in .NET Framework?

I have the following class. class Test{ public HashSet<string> Data = new HashSet<string>(); } I need to change the field "Data" from different threads, so I would like some opinions ...
kukab's user avatar
  • 2,243
218 votes
5 answers
140k views

C# Thread safe fast(est) counter

What is the way to obtain a thread safe counter in C# with best possible performance? This is as simple as it gets: public static long GetNextValue() { long result; lock (LOCK) { ...
JohnDoDo's user avatar
  • 4,850
208 votes
9 answers
176k views

Automating the InvokeRequired code pattern

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 ...
Tom Corelis's user avatar
  • 5,030
187 votes
15 answers
318k views

Thread-safe List<T> property

I want an implementation of List<T> as a property which can be used thread-safely without any doubt. Something like this: private List<T> _list; private List<T> MyT { get { // ...
Xaqron's user avatar
  • 30.6k
181 votes
4 answers
130k views

What Makes a Method Thread-safe? What are the rules?

Are there overall rules/guidelines for what makes a method thread-safe? I understand that there are probably a million one-off situations, but what about in general? Is it this simple? If a method ...
Bob Horn's user avatar
  • 34.1k
173 votes
4 answers
90k views

Are global variables thread-safe in Flask? How do I share data between requests?

In my application, the state of a common object is changed by making requests, and the response depends on the state. class SomeObj(): def __init__(self, param): self.param = param def ...
sayantankhan's user avatar
  • 2,251
171 votes
5 answers
124k views

Is iterating ConcurrentHashMap values thread safe?

In javadoc for ConcurrentHashMap is the following: Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect ...
Palo's user avatar
  • 10.7k
168 votes
4 answers
72k views

Is it OK to use Gson instance as a static field in a model bean (reuse)?

Here's the model I implemented: public class LoginSession { private static final Gson gson = new Gson(); private String id; private String name; private long timestamp; public ...
philipjkim's user avatar
  • 4,119
161 votes
12 answers
111k views

What does threadsafe mean?

Recently I tried to Access a textbox from a thread (other than the UI thread) and an exception was thrown. It said something about the "code not being thread safe" and so I ended up writing a delegate ...
158 votes
3 answers
91k views

Difference between -pthread and -lpthread while compiling

What is the difference between gcc -pthread and gcc -lpthread which is used while compiling multithreaded programs?
Vishnuraj V's user avatar
  • 2,849
152 votes
3 answers
106k views

To what degree does std::shared_ptr ensure thread-safety?

I'm reading http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html and some thread safety issues are still not clear for me: Standard guarantees that reference counting is handled thread safe ...
Goofy's user avatar
  • 5,307
148 votes
10 answers
207k views

How can I make a JUnit test wait?

I have a JUnit test that I want to wait for a period of time synchronously. My JUnit test looks like this: @Test public void testExipres(){ SomeCacheObject sco = new SomeCacheObject(); sco....
Kylar's user avatar
  • 9,196
148 votes
5 answers
142k views

Thread Safety in Python's dictionary

I have a class which holds a dictionary class OrderBook: orders = {'Restaurant1': None, 'Restaurant2': None, 'Restaurant3': None, 'Restaurant4': None} ...
nmat's user avatar
  • 7,571
145 votes
6 answers
64k views

Are non-synchronised static methods thread safe if they don't modify static class variables?

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 ...
Sled's user avatar
  • 18.8k
141 votes
8 answers
11k views

Is the != check thread safe?

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 ...
Narendra Pathai's user avatar
129 votes
8 answers
53k views

Is Random class thread safe?

Is it valid to share one instance of the Random class between multiple threads? And to call nextInt(int) from multiple threads in particular?
Shcheklein's user avatar
  • 6,139
127 votes
3 answers
20k views

Does const mean thread-safe in C++11?

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?
K-ballo's user avatar
  • 81.1k
120 votes
3 answers
60k views

What do each memory_order mean?

I read a chapter and I didn't like it much. I'm still unclear what the differences is between each memory order. This is my current speculation which I understood after reading the much more simple ...
user avatar
119 votes
7 answers
60k views

Find if the installed PHP is threadsafe or nonthreadsafe?

How do I find out whether the installed version of PHP is threadsafe or not thread safe? Please note that I'm not asking the difference between a threadsafe/non thread safe installation. I would like ...
Josh's user avatar
  • 1,337
116 votes
3 answers
28k views

Is SecureRandom thread safe?

Is SecureRandom thread safe? That is, after initializing it, can access to the next random number be relied on to be thread safe? Examining the source code seems to show that it is, and this bug ...
Yishai's user avatar
  • 91.4k
110 votes
8 answers
70k views

What's the best way of implementing a thread-safe Dictionary?

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, ...
GP.'s user avatar
  • 1,293
108 votes
4 answers
57k views

Threadsafe vs re-entrant

Recently, I asked a question, with title as "Is malloc thread safe?", and inside that I asked, "Is malloc re-entrant?" I was under the impression that all re-entrant are thread-safe. Is this ...
Alphaneo's user avatar
  • 12.4k
107 votes
4 answers
79k views

Is a HashMap thread-safe for different keys?

If I have two multiple threads accessing a HashMap, but guarantee that they'll never be accessing the same key at the same time, could that still lead to a race condition?
agentofuser's user avatar
  • 9,197
105 votes
8 answers
53k views

Why are local variables thread safe in Java

I was reading multi-threading in Java and I come across this Local variables are thread safe in Java. Since then I have been thinking How/Why local variables are thread safe. Can somebody please ...
Anand's user avatar
  • 21.1k
97 votes
7 answers
89k views

How to ensure thread safety of utility static method?

Is there any general way or rules exits by which we can ensure the thread safety of static methods specifically used in various Utility classes of any applications. Here I want to specifically point ...
Tapas Bose's user avatar
  • 29.5k
97 votes
3 answers
24k views

how to know what is NOT thread-safe in ruby?

starting from Rails 4, everything would have to run in threaded environment by default. What this means is all of the code we write AND ALL the gems we use are required to be threadsafe so, I have ...
CuriousMind's user avatar
  • 33.9k
96 votes
7 answers
12k views

Why is this class not thread safe?

class ThreadSafeClass extends Thread { private static int count = 0; public synchronized static void increment() { count++; } public synchronized void decrement() ...
das kinder's user avatar
  • 1,180
96 votes
3 answers
46k views

Is it safe to call a synchronized method from another synchronized method?

If a synchronized method calls another synchronized method, is it thread safe? void synchronized method1() { method2() } void synchronized method2() { }
user705414's user avatar
95 votes
4 answers
71k views

iphone ios running in separate thread

What is the best way to run code on a separate thread? Is it: [NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL]; Or: NSOperationQueue *queue = [...
Mike S's user avatar
  • 4,112
88 votes
4 answers
31k views

Safety of Thread.current[] usage in rails

I keep getting conflicting opinions on the practice of storing information in the Thread.current hash (e.g., the current_user, the current subdomain, etc.). The technique has been proposed as a way to ...
Giuseppe's user avatar
  • 5,308
88 votes
3 answers
4k views

lock(new object()) -- Cargo cult or some crazy "language special case"?

I'm reviewing some code written by a consultant, and while dozens of red flags have already popped up, I can't wrap my head around the following snippet: private void foo() { if (InvokeRequired) ...
user avatar
87 votes
9 answers
106k views

How do you implement a singleton efficiently and thread-safely? [duplicate]

The usual pattern for a singleton class is something like static Foo &getInst() { static Foo *inst = NULL; if(inst == NULL) inst = new Foo(...); return *inst; } However, it's my ...
user168715's user avatar
  • 5,559
87 votes
14 answers
218k views

Android - Best and safe way to stop thread

I want to know which is the best way to stop a thread in Android. I know I can use AsyncTask instead of it and that there is a cancel() method. I have to use Threads in my situation. Here is how I'm ...
Android-Droid's user avatar
86 votes
12 answers
81k views

Is malloc thread-safe?

Is the malloc() function re-entrant?
Alphaneo's user avatar
  • 12.4k
84 votes
2 answers
68k views

How to create a task (TPL) running a STA thread?

Using Thread is pretty straightforward Thread thread = new Thread(MethodWhichRequiresSTA); thread.SetApartmentState(ApartmentState.STA); How to accomplish the same using Tasks in a WPF ...
Michel Triana's user avatar
79 votes
4 answers
57k views

Is RestTemplate thread safe?

Is a Spring RestTemplate thread-safe? That is Is a RestTemplate a Strategy object that multiple connections can safely share. or Is a RestTemplate a connection object (like a data-base connection), ...
Raedwald's user avatar
  • 48k
77 votes
4 answers
58k views

how to make an application thread safe?

I thought thread safe, in particular, means it must satisfy the need for multiple threads to access the same shared data. But, it seems this definition is not enough. Can anyone please list out the ...
ashmish2's user avatar
  • 2,935
75 votes
5 answers
24k views

What is "Linearizability"?

Can anyone out there help me understand what Linearizability is? I need an explanation that is simple and easy to understand. I'm reading The Art of Multiprocessor Programming by Maruice Herilihy ...
unnknown's user avatar
  • 1,755
75 votes
2 answers
36k views

What is the difference between SynchronizedCollection<T> and the other concurrent collections?

How does SynchronizedCollection<T> and the concurrent collections in the System.Collections.Concurrent namespace differ from each other, apart from Concurrent Collections being a namespace and ...
Batrickparry's user avatar
  • 1,609
74 votes
5 answers
55k views

Is java.sql.Connection thread safe?

To rephrase the question: should I avoid sharing instances of classes which implement java.sql.Connection between different threads?
Boris Pavlović's user avatar
74 votes
2 answers
21k views

difference between standard's atomic bool and atomic flag

I wasn't aware of the std::atomic variables but was aware about the std::mutex (weird right!) provided by the standard; however one thing caught my eye: there are two seemingly-same (to me) atomic ...
hg_git's user avatar
  • 3,014

1
2 3 4 5
190