How to synchronize a static variable among threads running different instances of a class in Java?

There are several ways to synchronize access to a static variable. Use a synchronized static method. This synchronizes on the class object. public class Test { private static int count = 0; public static synchronized void incrementCount() { count++; } } Explicitly synchronize on the class object. public class Test { private static int count … 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

Synchronization vs Lock

If you’re simply locking an object, I’d prefer to use synchronized Example: Lock.acquire(); doSomethingNifty(); // Throws a NPE! Lock.release(); // Oh noes, we never release the lock! You have to explicitly do try{} finally{} everywhere. Whereas with synchronized, it’s super clear and impossible to get wrong: synchronized(myObject) { doSomethingNifty(); } That said, Locks may be … Read more

Is multi-thread output from System.out.println interleaved

Since the API documentation makes no mention of thread safety on the System.out object nor does the PrintStream#println(String) method you cannot assume that it is thread-safe. However, it is entirely possible that the underlying implementation of a particular JVM uses a thread-safe function for the println method (e.g. printf on glibc) so that, in reality, … Read more

C++0x has no semaphores? How to synchronize threads?

You can easily build one from a mutex and a condition variable: #include <mutex> #include <condition_variable> class semaphore { std::mutex mutex_; std::condition_variable condition_; unsigned long count_ = 0; // Initialized as locked. public: void release() { std::lock_guard<decltype(mutex_)> lock(mutex_); ++count_; condition_.notify_one(); } void acquire() { std::unique_lock<decltype(mutex_)> lock(mutex_); while(!count_) // Handle spurious wake-ups. condition_.wait(lock); –count_; } bool … Read more