Synchronized objects when repeating ArrayList

Say I have the following scenario:

final int index = 10; Phone phone = phoneList.get(index); synchronized(phone) { //some code runs here } 

So, if the phone object (which received the phoneList.get () method) is blocked, another thread can execute the method:

 phoneList.remove(index); 

and reset the telephone object at the specified index?

+4
source share
6 answers

Yes. why not?

But still, the phone will point to the same object. that is, the object is removed from the list, but jvm still has a link to it.

+3
source

One operation has nothing to do with another: synchronized does not protect access to any particular object. If your remove operation is in a synchronized block that uses the same object as the lock, then it will have to wait; if it fails to delete the object without affecting the synchronized block, which uses it as a lock. Removing an object from the list will not turn the object into garbage until its monitor is blocked by a thread.

+3
source

Yes.

Since you are synchronizing your Phone instance, this is possible. Another thread may delete the same Phone object from the ArrayList . But the Phone link will point to the same instance.

So that no other thread can access your list from another place, synchronize in the list itself -

 synchronized(phoneList) { //some code runs here } 
+2
source

Ofcourse. Phone lock does not block the list.

In addition, to remove an item from the list, you do not need to use this item. Removing is as simple as:

 backingArray[i] = null; 
+2
source

Here, it simply provides synchronization for a group of statements inside synchronized and never cares about the resulting phone instance. It is possible to delete the phone object from phoneList . But remember that Java does not delete an object from memory until some link remains.

+2
source

When you call phoneList.get (index), it gives an object reference from the list to the Phone object.

Since only the telephone object is synchronized, you can remove items from the list. Therefore, you will NOT receive an UnsupportedOperationException when you try to remove items from the list.

But if the link is lost or null. You can get a NullPointerException when trying to work with a phone object.

+1
source

Source: https://habr.com/ru/post/1500491/


All Articles