P3nnyw1se
P3nnyw1se

Reputation: 13

Understanding shared Objects with Threads and synchronization

I am new to Java and reading about Synchronization I have a question

I'm not quite sure how this still works so I would like to ask:

e.g. I have a class called 'Math' with synchronized methods of adding and removing then create an object of it

Math m = new Math();

and I start 3 threads and pass this object (m) to all. I know that they will work into the same object and each thread will queue as expected

but what if each thread created their own object?

Math m = new Math();

they wouldn't work with the same synchronized methods right?

Upvotes: 1

Views: 132

Answers (3)

WoooHaaaa
WoooHaaaa

Reputation: 20470

The only thing here you need to understand is Class level lock and Instance level lock.

1. Instance Level Lock

Like in your first case, all threads share the same object, so every thread need to obtain the only one lock to be able to invoke those methods.

e.g.

Class Math {
    synchronized public void add(){}
    synchronized public void decrease(){}
}

Both of add and decrease are instance method. So if two threads are operate in different instance, they will not effect each other.

2. Class Level Lock

Class Math {
    synchronized public static void add(){}
    synchronized public static void decrease(){}
}

In this case, add and decrease can be invoked without create a Math Object, they a Class level lock, all threads use Math.add or Math.decrease should obtain the same lock.

Upvotes: 0

Jeb
Jeb

Reputation: 3799

If each thread created their own Math object, they would all be independent of each other; they wouldn't be shared - hence not work with the same synchronised methods (unless they are static methods as Mani has pointed out). However, be careful if the Math object has a static member which is used in the synchronised methods - you will still need to provide a locking construct around it if any of the methods change the state of it.

Upvotes: 0

serdar
serdar

Reputation: 984

No they didn't work with same methods. But it can depend on Math object.

Upvotes: 1

Related Questions