Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization on static and instance method

I am confused about synchronizing an instance method and a static method. I want to write a thread safe class as follow :

public class safe {

  private final static ConcurrentLinkedQueue<Object> objectList=
      new ConcurrentLinkedQueue<Object>();

  /**
   * retrieves the head of the object and prints it
   */
    public synchronized static  void getHeadObject() {
      System.out.println(objectList.peek().toString());

    }

    /**
     * creates a new object and stores in the list.
     */
    public synchronized void addObject() {
      Object obj=new Object();
      objectList.add(obj);

    }
}

Synchronizing on a static method will lock on safe.class lock and synchronizing on a instance method will lock on this .and hence an inconsistent state will be reached.

If I want to achieve a consistent state for a below code snippet how can that be achieved?

like image 813
Gayatri Avatar asked Oct 07 '22 10:10

Gayatri


1 Answers

First, ConcurrentLinkedQueue does not require explicit synchronization. See this answer.

Second, you always can synchronize object you are accessing:

public class safe {

      private final static ConcurrentLinkedQueue<Object> objectList=
          new ConcurrentLinkedQueue<Object>();

      /**
       * retrieves the head of the object and prints it
       */
     public static  void getHeadObject() {
         synchronized(objectList){
          System.out.println(objectList.peek().toString());
         }

     }

        /**
         * creates a new object and stores in the list.
         */
     public void addObject() {
          Object obj=new Object();
       synchronized(objectList){
          objectList.add(obj);
       }

     }
}
like image 184
Aleksandr Kravets Avatar answered Oct 12 '22 09:10

Aleksandr Kravets