Preator Darmatheon
Preator Darmatheon

Reputation: 69

Are method level singleton instances Thread safe?

Are the operations on obj below thread safe? I know that method level variables and instances go on each thread's stack - but im not sure what will happen when the local variable is a singleton. foo() is called in a webservice call. I'm curious whether this is thread-safe?

public void foo() {
    SomeObject obj = getSomeObject();  
    obj.doSomething();   // Would this be thread safe?
}

private SomeObject getSomeObject() {
    // returns singleton
    SpringContext.getBean("someObject");
}

class SomeObject {
    int x;
      ...

    // Not synchronized
    public void doSomething() {

    }
}

Upvotes: 1

Views: 274

Answers (3)

John Vint
John Vint

Reputation: 40256

Method/Thread locality may be lost completely when you make any static reference. Since the reference is static the local field pointing to the static reference is not on the thread stack, it may in fact be referenced by other threads.

You have the same thread-safety effect if the Object was assigned globally instead of thread-local.

final SomeObject obj = getSomeObject();
public void foo() {
    obj.doSomething();  
}

private SomeObject getSomeObject() {
    // returns singleton
    SpringContext.getBean("someObject");
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

It depends on what you mean by "thread-safe". If SomeObject.doSomething() mutates the instance in an unsafe way, then no, it's not safe. Two different threads could obtain references to the same object.

Basically, unless SomeObject is designed to be used from multiple threads concurrently, you shouldn't be making it a singleton.

Upvotes: 6

Gray
Gray

Reputation: 116818

It is thread safe only if the SomeObject is itself thread-safe. If, for example, you read and can change the value of x in the doSomething() call then it would not be thread safe unless it was appropriately locked.

Without knowing more about SomeObject it is impossible to tell exactly whether or not you would have a problem.

Upvotes: 4

Related Questions