How to make file creation an atomic operation?

Write data to a temporary file and when data has been successfully written, rename the file to the correct destination file e.g f = open(tmpFile, ‘w’) f.write(text) # make sure that all data is on disk # see http://stackoverflow.com/questions/7433057/is-rename-without-fsync-safe f.flush() os.fsync(f.fileno()) f.close() os.rename(tmpFile, myFile) According to doc http://docs.python.org/library/os.html#os.rename If successful, the renaming will be an … Read more

What operations are atomic in C#?

For something more complete/detailed: Reads and writes to 32-bit value types are atomic: This includes the following intrinsic value (struct) types: bool, char, byte, sbyte, short, ushort, int, uint, float. The following types (amongst others) are not guaranteed to be atomic: decimal, double, long, ulong. e.g. int x; x = 10; // atomic decimal d; … Read more

What is the difference between atomic / volatile / synchronized?

You are specifically asking about how they internally work, so here you are: No synchronization private int counter; public int getNextUniqueIndex() { return counter++; } It basically reads value from memory, increments it and puts back to memory. This works in single thread but nowadays, in the era of multi-core, multi-CPU, multi-level caches it won’t … Read more

Is file append atomic in UNIX?

A write that’s under the size of ‘PIPE_BUF’ is supposed to be atomic. That should be at least 512 bytes, though it could easily be larger (linux seems to have it set to 4096). This assume that you’re talking all fully POSIX-compliant components. For instance, this isn’t true on NFS. But assuming you write to … Read more

Practical uses for AtomicInteger

There are two main uses of AtomicInteger: As an atomic counter (incrementAndGet(), etc) that can be used by many threads concurrently As a primitive that supports compare-and-swap instruction (compareAndSet()) to implement non-blocking algorithms. Here is an example of non-blocking random number generator from Brian Göetz’s Java Concurrency In Practice: public class AtomicPseudoRandom extends PseudoRandom { … Read more

When to use volatile with multi threading?

Short & quick answer: volatile is (nearly) useless for platform-agnostic, multithreaded application programming. It does not provide any synchronization, it does not create memory fences, nor does it ensure the order of execution of operations. It does not make operations atomic. It does not make your code magically thread safe. volatile may be the single-most … Read more