Basically i was going trough a multithreading guide in developers.android.com when i saw something that confused me...(i am reffering to this article
http://developer.android.com/training/multiple-threads/create-threadpool.html
)
In the Define the Thread Pool Class section where they mention that the class should have a private constructor in order to make it singleton, the writer claims that by doing this the code would not require synhronization. I am confused why this is thread safe, as altough it is a singleton it can still be referenced by multiple threads simultaneously causing memory consistency errors etc.
What they mean is:
Since the constructor is private only a method inside the class itself may create an instance of that class
The only instance of that class created is through:
static
{
// Creates a single static instance of PhotoManager
sInstance = new PhotoManager();
}
The static { ... } block is thread safe because it is executed by the class loader, which is synchronized
Related
I think I understand the Singleton pattern. It seems to me that there are many cases where more than one user is accessing the single instance that the pattern enforces. But is there a refinement that prevents that instance from being used (even read-only) while another user is accessing it or is that still a Singleton?
EDIT: So if a Singleton does not prevent more than one thread from accessing it, is there a standard way to enforce this further functionality. To be clear, if a thread attempts to get the instance before the first thread that accessed the Singleton is done, an exception is thrown or the thread blocks?
A Singleton can only be instantiated once. This says nothing about the number of (simultaneous) users it has.
What you say: a class which instance can have only one user, this means: per user, there is a different instance, not that only one user can use it.
So: there's a big difference there.
No. The singleton pattern makes sure that there's only one instance of a class. It does not do any kind of synchronization.
You are of corse free to implement this in your class by using synchronized methods.
You can use this aproach of thread safe singleton:
https://stackoverflow.com/a/16106598/327786
public class CassandraAstyanaxConnection {
private static class Holder {
static final CassandraAstyanaxConnection INSTANCE = new CassandraAstyanaxConnection();
}
public static CassandraAstyanaxConnection getInstance() {
return Holder.INSTANCE;
}
// rest of class omitted
}
In Brian Goetz's article about safe construction techniques you could read:
[...] often when an object owns a thread, either that thread is an inner class or we pass the this reference to its constructor (or the class itself extends the Thread class). If an object is going to own a thread, it is best if the object provides a start() method, just like Thread does, and starts the thread from the start() method instead of from the constructor. While this does expose some implementation details (such as the possible existence of an owned thread) of the class via the interface, which is often not desirable, in this case the risks of starting the thread from the constructor outweigh the benefit of implementation hiding.
I guess that with the following code there shouldn't be any problem. Since it is not an inner class nor I am passing a reference of this. But I want to be sure.
private Controller controller;
private View view;
public Facade() {
view = new View();
controller = new Controller(view);
controller.start();
}
I keep getting NetBeans warnings though... So is this code safe or unsafe?
The main reason do not start thread in constructor - do not expose "this" before "this" is created (after constructor executed). In your code I do not see such code like:
new Thread(this);
So it should be fine.
I am new to java thread application please tell me How to write program, every thread access same list of object in multithreading application?
is there any good link to read?
You can make sure your List (or any Collection) will be thread safe by using the relevant methods in the Collections class.
From the API:
public static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list.
For example
static List mySharedList = Collections.synchronizedList(new ArrayList());
Try to access your list with same instance or make it static and make it Synchronized to make your list thread-safe.
You can use a static list so that there would be only one copy at any time. Also make sure to use syncronised methods for thread-safe.
To access the same instance of your list from all threads, make it static. Eg:
private static List myList;
Then make the accessing method thread-safe (i.e. Make it so that only one thread can access it at one time, so as to avoid conflicts). Eg:
public static synchronized updateList(String parameters) {
// Do something
}
Yes, all threads are able to access the same instance of any objects (incl. classes). Because a memory space is created on per-application (i.e. per-process) basis. Then a process contains all threads inside, incl. implicit 'main' one, with shared memory space.
If an object is used in one thread only, there are no any concurrency issues. You need no any 'synchronization', locking etc. But sometimes you may have to share something between thread. If both reading and writing can be done in a few threads simultaneously, it means you need synchronize by this object to deal with so called 'racing'.
You don't have to make a field as static for a shared object to make it thread-safe. If necessary, you can just pass this object as a parameter into a class which extends Thread class (or it may be even a local variable in enclosing class method in case of anonymous class, etc.)
So all you need is just synchronize by this object. You can synchronize either explicitly inside a method:
synchronized (obj) {
// doing a thread-safe stuff
}
or you can make a method synchronized entirely for an obj's class using such method modifier. In this case it will be synchronized implicitly and automatically on invocation of the method like "synchronized (this) {..}" block:
public void synchronized methodFoo() {
}
As for reading, I read 'Java in a Nutshell', chapter 5.7. "Threads and Concurrency". It was very helpful for me because of overview of all multi-threading possibilities in Java.
Among online resources, official Sun/Oracle's tutorial may be helpful for the beginners: http://docs.oracle.com/javase/tutorial/essential/concurrency/ (which has been already mentioned in another answers).
Is the following code threadsafe ?
public static Entity getInstance(){
//the constructor below is a default one.
return new Entity();
}
Assuming the constructor itself is thread-safe, that's fine.
It would be very unusual for a constructor not to be thread-safe, but possible... even if it's calling the default auto-generated constructor for Entity, the base constructor may not be thread-safe. I'm not saying it's likely, just possible :)
Basically there's no magic thread-safety applied to static methods or instance methods or constructors. They can all be called on multiple threads concurrently unless synchronization is applied. If they don't fetch or change any shared data, they will generally be safe - if they do access shared data, you need to be more careful. (If the shared data is immutable or only read, that's generally okay - but if one of the threads will be mutating it, you need to be really careful.)
Only static initializers (initialization expressions for static variables and static { ... } blocks directly within a class) have special treatment - the VM makes sure they're executed once and only once, blocking other threads which are waiting for the type to be initialized.
It depends on the details of the Entity constructor. If the Entity constructor modifies shared data, then it is not.
It's probably thread safe, but what's the point? If you're just using a factory method to redirect to the default constructor then why not use the constructor in the first place? So the question is: what are you trying to achieve? The name getInstance() suggests a singleton (at least that's common practice), but you clearly don't have a singleton there. If you do want a singleton, use a static inner holder class like this:
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
private static final class InstanceHolder {
public static final Singleton INSTANCE = new Singleton();
}
}
but if you don't, why bother with such a factory method, as you're not adding any value (method name semantics, object pooling, synchronization etc) through it
Thread safety is about access to shared data between different threads. The code in your example doesn't access shared data by itself, but whether it's thread-safe depends on whether the constructor accesses data that could be shared between different threads.
There are a lot of subtle and hard issues to deal with with regard to concurrent programming. If you want to learn about thread safety and concurrent programming in Java, then I highly recommend the book Java Concurrency in Practice by Brian Goetz.
Multiple threads could call this method and each one will get an unique instance of 'Entity'. So this method 'per se' is thread safe. But if there is code in the constructor or in one of the super constructors that is not thread safe you might have a safety problem anyhow.
I'm using a static code block to initialize some controllers in a registry I have. My question is therefore, can I guarantee that this static code block will only absolutely be called once when the class is first loaded? I understand I cannot guarantee when this code block will be called, I'm guessing its when the Classloader first loads it. I realize I could synchronize on the class in the static code block, but my guess is this is actually what happens anyway?
Simple code example would be;
class FooRegistry {
static {
//this code must only ever be called once
addController(new FooControllerImpl());
}
private static void addController(IFooController controller) {
// ...
}
}
or should I do this;
class FooRegistry {
static {
synchronized(FooRegistry.class) {
addController(new FooControllerImpl());
}
}
private static void addController(IFooController controller) {
// ...
}
}
Yes, Java static initializers are thread safe (use your first option).
However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.
This is a trick you can use for lazy initialization
enum Singleton {
INSTANCE;
}
or for pre Java 5.0
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton instance() {
return SingletonHolder.INSTANCE;
}
}
As the static block in SingletonHolder will run once in a thread safe manner you don't need any other locking. The class SingletonHolder will only get loaded when you call instance()
In usual circumstances everything in the static initialiser happens-before everything that uses that class, so synchronisation is not usually necessary. However, the class is accessible to anything that the static intiailiser calls (including causing other static initialisers to be invoked).
A class can be loaded by a class loaded but not necessarily initialised straight away. Of course, a class can be loaded by multiples instances of class loaders and thereby become multiple classes with the same name.
Yes, sort of
A static initializer only gets called once, so by that definition it's thread safe -- you'd need two or more invocations of the static initializer to even get thread contention.
That said, static initializers are confusing in many other ways. There's really no specified order in which they're called. This gets really confusing if you have two classes whose static initializers depend on each other. And if you use a class but don't use what the static initializer will set up, you're not guaranteed the class loader will invoke the static initializer.
Finally, keep in mind the objects you're synchronizing on. I realize this isn't really what you're asking, but make sure your question isn't really asking if you need to make addController() thread-safe.
Yes, Static initializers are run only once. Read this for more information.
So basically, since you want a singleton instance, you should do it more or less the old-fashioned way and make sure your singleton object is initialised once and only once.