• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singelton, static, and concurrency

 
Greg Blajian
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I apologize if this question is too simple for the intermediate forum. Given the following code
<code>
public class A
{
private String b = {"a", "b", "c", "d"};
private static A a = new A();
public static A getInstance()
{
return a;
}

int findGoofy(String x)
{
int j = -1;
for (int i = 0; i < b.length; ++i)
{
if (c.equals(b[i])) j = i;
}
return j;
}
}
</code>

if a method in one thread wants to look for "a" and a method in another thread looks for "d" could the caller looking for "d" end up with 1 or -1 or the one looking for "a" end up with 4 or -1? Does the static modifier on the singleton instance guarantee thread safety in the findGoofy method? Would I be better off just making findGoofy static and not having a singleton at all? Would there be different instances of x and i on the stack/heap for each thread that would ensure that this isn't really a problem regardless of whether anything is declared static or not?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Joke names and "handles" aren't acceptable here. You can change your display name here. Thanks for your cooperation.

Now, as to your question: singleton or not, static or not, there are no thread safety issues here at all. Every invocation of any method (static or not) gets its very own distinct copy of all the local variables. In your case, the multiple invocations would all be sharing the member array "b", but that's just fine because it's never modified, only read. Thread safety is only an issue when you're talking about shared data that can be modified; the "safety" issues all boil down to not all threads seeing the changes correctly or simultaneously. And again, local variables (x, i, and j) are never shared.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic