user2801442
user2801442

Reputation: 73

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!

Upvotes: 1

Views: 64

Answers (2)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

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.

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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.

Upvotes: 2

Related Questions