How to implement thread-safe lazy initialization?

For singletons there is an elegant solution by delegating the task to the JVM code for static initialization. public class Something { private Something() { } private static class LazyHolder { public static final Something INSTANCE = new Something(); } public static Something getInstance() { return LazyHolder.INSTANCE; } } see http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom and this blog post … Read more

What is the difference between SynchronizedCollection and the other concurrent collections?

The SynchronizedCollection<T> class was introduced first in .NET 2.0 to provide a thread-safe collection class. It does this via locking so that you essentially have a List<T> where every access is wrapped in a lock statement. The System.Collections.Concurrent namespace is much newer. It wasn’t introduced until .NET 4.0 and it includes a substantially improved and … Read more

Multithreading program stuck in optimized mode but runs normally in -O0

Two threads, accessing a non-atomic, non-guarded variable are U.B. This concerns finished. You could make finished of type std::atomic<bool> to fix this. My fix: #include <iostream> #include <future> #include <atomic> static std::atomic<bool> finished = false; int func() { size_t i = 0; while (!finished) ++i; return i; } int main() { auto result=std::async(std::launch::async, func); std::this_thread::sleep_for(std::chrono::seconds(1)); … Read more

What is “Linearizability”?

A picture is worth 1000 words. The first SELECT statement reads the value of 50, while the second SELECT reads the value of 10 since in between the two read operations a write operation was executed. Linearizability means that modifications happen instantaneously, and once a registry value is written, any subsequent read operation will find … Read more

How to stop a thread created by implementing runnable interface?

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc. Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)