Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static method and thread safety

Tags:

java

Is the following code threadsafe ?

    public static Entity getInstance(){
//the constructor below is a default one.
     return new Entity();
    }
like image 385
Anthos Avatar asked Dec 13 '22 21:12

Anthos


1 Answers

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.

like image 119
Jon Skeet Avatar answered Dec 27 '22 13:12

Jon Skeet