L4zl0w
L4zl0w

Reputation: 1097

Java: thread safe class instances

I have the following two classes:

public class MyClass {

   public static void faceTheWorld(String Input){
      SafeClass sC = new SafeClass();
      sC.workWithInput(Input);
   }
}

public class SafeClass {
   public void workWithInput{String allInp)

   work with allInp...
}

My question is. If I call MyClass.FaceTheWorld() several times at the very same time, will it always create a new class instance of SafeClass or will it try to create the same instance called 'sC' all the time?

Would I need to create an array of instances instead to make avoid creating the same instance at the same time? How would this look in Java?

Ultimately what I'm trying to achieve is that when I call FaceTheWorld with the 'Input' it would always make sure that 'Input' is thread safe e.g. no other instances can modify/access it.

I make SafeClass synchronized, would that solve the problem?

Many thanks

Upvotes: 2

Views: 154

Answers (3)

Michał Tabor
Michał Tabor

Reputation: 2467

It will always create new instance no matter how often will you initialize it. Synchroznied keyword isn't solution to your problem.

Upvotes: 1

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

It will create a new instance every time, so it should be thread safe, barring any other weird things that you aren't telling us (like that object making use of static variables within the method you call). But if you are afraid it will be using the same object on each call, it will not.

Upvotes: 1

Martin Braun
Martin Braun

Reputation: 602

As long as you don't access variables that can be changed by other threads (members of classes, or static variables) you will never have any race conditions if you just create a new instance in a static method (or any other method) because each method has its own stack of variables.

And to be concrete to your question:

It will always create a new instance.

Upvotes: 1

Related Questions