Synchronization Question / Issue

E

exits funnel

Hello,

I've inherited the following bit of code which loads a set of
application configuration parameters from a properties file on the
classpath. Life was good until we started running in a multithreaded
environment. Now we're seeing the occasional problem with the values
were accessing from the Properties instance returned by this method.
All access to the Properties object is read only so I'm pretty sure
there are no multithreading issues there. I would guess that the
problem is with the lazy initialization bit. Two questions then.
First, is my assumption about the thread safety of concurrent reads on
the Properties object correct? Second, assuming the problem is the lazy
initialization, how best to fix it? The obvious solution is to
synchronize getXMLProperties( ) but I'm wondering if this will have a
significant performance cost? If so, it seems kind of silly considering
I really only care that it's synchronised the first couple of what could
possibly be millions of calls over the lifetime of the program. So, can
anyone suggest a better approach short of synchronizing the method?
Thanks in advance and I apologize for rambling :)

// BEGIN CODE
static java.util.Properties getXMLProperties()
{
if (xmlProps == null) // Lazy initialization
{
xmlProps = new java.util.Properties();
try
{
InputStream rInputStream;
rInputStream =
MyClass.class.getResourceAsStream("\props.properties");
if (rInputStream != null)
{
rInputStream = new BufferedInputStream(rInputStream);
xmlProps.load(rInputStream);
}
}
catch (Exception e) { }
}

return xmlProps;
}

private static Properties xmlProps;
// END CODE

-exits
 
A

ak

I would write syncronized method loadXMLProperties() and call it from
getXMLProperties():

// BEGIN CODE
static java.util.Properties getXMLProperties()
{
if (xmlProps == null) // Lazy initialization
{
xmlProps = loadXMLProperties();
}
return xmlProps;
}

synchronized java.util.Properties loadXMLProperties() {
xmlProps = new java.util.Properties();
try
{
InputStream rInputStream;
rInputStream =
MyClass.class.getResourceAsStream("\props.properties");
if (rInputStream != null)
{
rInputStream = new BufferedInputStream(rInputStream);
xmlProps.load(rInputStream);
}
}
catch (Exception e) { }
}

return xmlProps;
}

private static Properties xmlProps;
// END CODE
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top