aspose file tools*
The moose likes Java in General and the fly likes Singelton, static, and concurrency Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Singelton, static, and concurrency" Watch "Singelton, static, and concurrency" New topic
Author

Singelton, static, and concurrency

Greg Blajian
Greenhorn

Joined: Aug 31, 2005
Posts: 5
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singelton, static, and concurrency