Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

are static properties thread safe?

Status
Not open for further replies.

jemminger

Programmer
Jun 25, 2001
3,453
US
suppose i have a class:
Code:
import org.apache.oro.text.perl.Perl5Util;

class Foo {
  static Perl5Util util = new Perl5Util();

  /**
   * replace "foo" with "bar" in str
   */
  public static String replaceFoo(String str) {
    return util.substitute("s#foo#bar#gi", str);
  }
}

because the property util and the method replaceFoo are static, is there a chance that under heavy load, one thread might receive another thread's result?

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
 
'static' doesn't influence thread-safety.

util.substitute might have a static variable status, which - let's assume - is a boolean, and is true in the beginning.

you call substitute from one thread, and while processing, another thread gets invoked, changing the status to false, now the first thread is being called again, and continues.

But if the method doesn't depend on such status, it needn't be static at all, to return the expected result.

Without knowing the implementation of util.substitute, we may only guess.

seeking a job as java-programmer in Berlin:
 
If you make an object static (Perl5Util) then it means there will only be one instance ever instantiated in the JVM.

Whether or not a method is thread-safe depends on how you write the method. If your method relies on variables outside of the scope of the method (ie other methods running in other threads can update that variable), then your method will not be thread-safe. But if your method's variables are contained within the method scope, then it will be safe.

If you are worried about thread-safety, then just create a new object each time - which means all its variables will in effect be allocated to the heap for each object lifetime.

Why make Perl5Utils static anyway ?



--------------------------------------------------
Free Database Connection Pooling Software
 
sedj,

the method only relies on its arguments, so i guess i should be ok.

i made it static because that makes it ~4 times faster in repeated calls, not having to create it each time.


=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
 
well it would I guess, as you are not allocating and deallocating memory on the heap !



--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top