Throw an exception and sync

I have a method in which many threads are accessed in parallel, which uses a class with two synchronized methods that I do not control. getObject and createNewObject. I want to be sure that I am not creating multiple objects (MyObject).

MyObject obj;
public void method1() {
   obj = getObject("key");
   if (obj == null)
      obj = createNewObject("key");
  }

this, I think, will not work, since the thread can be paused between the get and create methods so that another thread can enter and create the object. The synchronized createNewObject method fixes this by checking if an already existing object with the name "key" exists and throws an exception in this case.

Which of the following methods will be proposed? Performance, safety and design. I heard that the double lock type (method 3) does not work? Maybe I should just use method1?

, . , ?

MyObject obj;
public synchronized void method1() {
   obj = getObject("key");
   if (obj == null)
      obj = createNewObject("key");
  }

public void method2() {
   obj = getObject("key");
   if (obj == null)
       try {
          obj = createNewObject("key");
       } catch (Exception e) { // ops, someone already created object "key"
            obj = getObject();
       }
  }

public void method3() {
   obj = getObject("key");
   if (obj == null)
       obj = getObj("key");
}
public synchronized MyObject getObj(String key) {
    MyObject obj = getObject(key);
    if (obj == null)
        obj = createNewObject(key);
    return obj;
 }
+3
6

, , - , , , getObject() , . , "/ ", "/ ", . , . 1() .

UPDATE

2() , : obj, . , obj , , 2(), method2() .

obj volatile, , ( 100% , ), getObject() , " ". getObject() , , . , obj. , obj, , .

. - , - , "".

+4

method1, , . , , . , , , , - .

+8

/ . /. / , , .

+3

EDIT: Double lock lockom, ,

---- ----

:

Object obj;

public Object getObject() {
    if( obj == null ) {
        synchronized(this) { // or on something else
            if( obj == null ) {
                obj = createObject();
            }
        }
    }
    return obj;  
}   

private Object createObject() {
    ...
} 

, , .

0

, createNewObject, 1 , -, . , createNewObject . , , , . , , , , .

0

, , :

private static class LazySomethingHolder {
    public static Something something = new Something();
}

public static Something getInstance() {
    return LazySomethingHolder.something;
}

concurrency .

0

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


All Articles