简体   繁体   中英

Does a getter( ) to shared data that doesn't change need to be synchronized?

Imagine I have this class:

public class SynchTest
{
  private static Object[] objs = new Object[3];

  static
  {
    objs[0] = new Object( );
    objs[1] = new Object( );
    objs[2] = new Object( );
  }

  public static Object getObject(int i)
  {
    return objs[i]
  }
}

and that objects running in multiple threads call the method getObject(int i). In this case, is it necessary to declare getObject(int i) syncchronized? I wouldn't think so because the objs array is initialized in a static block and never changed. But I'd like a sanity check :)

Thanks in advance!

You are correct, when an object is initialized in a static initialization block and is never written after that there is no need to make your getter synchronized .

Note that this does not make your program thread-safe: although the access to elements of the object array does not need synchronization, access to the individual object properties may need to be synchronized if these objects are mutable .

This answer is totally wrong! But I've left it here because the reasons why it's wrong took me by surprise. See the comment thread for more.


Assuming the data that is "gotten" is immutable, or you know it won't be changed by the threads, then so long as the data is set before any other threads are in a state to call the getter, then you are fine.

In general, data that is only read by multiple threads is always thread-safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM