Thread Safe Singletons in Java

Answer 1: static synchronized methods use the class object as the lock – ie in this case Singleton.class. Answer 2: The java language, among other things: loads classes when they are first accessed/used guarantees that before access to a class is allowed, all static initializers have completed These two facts mean that the inner static … Read more

What does the C++ compiler do to ensure that different but adjacent memory locations are safe to be used on different threads?

This is hardware-dependent. On hardware I am familiar with, C++ doesn’t have to do anything special, because from hardware perspective accessing different bytes even on a cached line is handled ‘transparently’. From the hardware, this situation is not really different from char a[2]; // or char a, b; In the cases above, we are talking … Read more

Java synchronized method

First of all, forget about synchronized methods. A so-called synchronized method… synchronized AnyType foobar(…) { doSomething(); } Is nothing but a shortcut way of writing this: AnyType foobar(…) { synchronized(this) { doSomething(); } } There is nothing special about the method in either case. What is special is the synchronized block, and what a synchronized … Read more

Is a reference assignment threadsafe?

Yes, reference updates are guaranteed to be atomic in the language spec. 5.5 Atomicity of variable references Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list … Read more

How do I prove programmatically that StringBuilder is not threadsafe?

Problem I am afraid the test you have written is incorrect. The main requirement is to share the same StringBuilder instance between different threads. Whereas you are creating a StringBuilder object for each thread. The problem is that a new Threadsafe() initialises a new StringBuilder(): class Threadsafe { … StringBuilder sb = new StringBuilder(str); … … Read more

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