Are static nested classes thread-safe?

There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
public class SomeMultiThreadedWebController {
public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
    simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
protected static class SimpleQueryBuilder {
         private String queryString;
         private Map<String, Object> params = new HashMap<String, Object>();
         public SimpleQueryBuilder(String queryString) {
              this.queryString = queryString;
         public SimpleQueryBuilder addParameter(String name, Object value) {
              params.put(name, value);
              return this;
         public Query createQuery(EntityManager em) {
              Query query = em.createQuery(queryString);
              for (Entry<String, Object> entry : params.entrySet()) {
                   query.setParameter(entry.getKey(), entry.getValue());
              return query;
    public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
         return new SimpleQueryBuilder(queryString);
}Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.

Hello,
I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
Let me correct this (essentially, incorrect uses of the terminology):
I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
Thus any synchronized method(With the limit stated above)
or immutable member (like primitive type) are thread-safe.
Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
Additional considerations:
1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
Edited by: jduprez on Mar 4, 2010 9:53 AM

Similar Messages

  • Static nested class VS non-static nested class ??

    we know static method can be called without creating an object and static variables are shared among objects.
    what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • Static nested class

    Hi there.
    Im playing around with static nested classes:
    class OuterC {
         int x = 10;
         static class Nest {
              void doStuff() {
                   System.out.println("Going");
                   //System.out.println("Should be allowed print: " + x);
                   doOtherStuff();
              public void doOtherStuff() {
                   System.out.println("Doing Stuff!");
    public class Test {
         static class OtherNest {
              void arbitraryMethod() {
                   System.out.println("Going to do arbitrary stuff...");
         public static void main(String[] args) {
              OuterC.Nest n = new OuterC.Nest();
              n.doStuff();
              OtherNest on = new OtherNest();
              on.arbitraryMethod();
    }//close TestWhen I uncomment the statement to print out the instance variable x of class OuterC
    I get a "cannot access non-static..." error, which is fine. I expect that.
    But why can I run the doOtherStuff() method from the static nested class Nest?
    doOtherStuff() is after all an instance method...
    Many Thanks & regards!
    Edited by: Boeing-737 on May 29, 2008 10:27 AM
    Dont bother replying, I see the error now. The method is defined as a member within the nested
    class. Apologies, I didn't spot that. My mistake.
    Thanks.
    Edited by: Boeing-737 on May 29, 2008 10:28 AM

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • Why a static nested class instead of a static block?

    What difference does it make: using a static nested class on a static block?

    Surya-2010 wrote:
    What difference does it make: using a static nested class on a static block?Do you mean static initialization block?
    They're different concepts. A static initialization block is part of the construction machinery of a class. A static nested class is a class you want to treat as part of another class.

  • Are methods in the Graphics class Thread Safe

    Can methods from the Graphics class (.e.g. drawImage(), drawString(), ect..) be called from any thread? In other words, can two threads that refer to the same Graphics object step on each other methods calls?
    TIA,
    DB
    Edited by: Darth_Bane on Apr 27, 2009 1:44 PM

    No,
    They are GUI activities so you should call them from the Swing Thread ( Event Disptach Thread)
    Now for the JComponent the following are thread safe:
    repaint(), revalidate, invalidate which can be called from any thread.
    Also the listener list can be modified from any thread addListenerXX or removeListenerXX where XX is ListenerType
    Regards,
    Alan Mehio
    London, UK

  • Private static nested class

    Hi everyone,
    I'm practicing nested classes. I've written this simple class:
    public class OuterClass {
      private static class InnerClass {
         private InnerClass() {
            System.out.println("in constructor" }
    } and another simple class to test:
    public class TestClass {
      public static void main(String[] args) {
            OuterClass.InnerClass in=   new OuterClass.InnerClass();
    }All classes compile and main method runs with no problem. Now I wonder what is the meaning of the private modifier here ??
    Thanks

    Ok, I'm using Oracle's JDeveloper 3.2 ( jdk1.2.2). The code I posted compiles and runs with no errors in Jdeveloper.
    However, I tested this on the command line ( using javac directly ) and it does not compile !

  • Problem instantiating static nested class

    How come this doesn't work?
    public class A {
        public static class B {
    public class Test {
        A.B test = new A.B(); 
    }The errors i got are:
    -Not an enclosing class: A
    -No enclosing instance of type A is in scope.
    TIA

    The code you posted compiled just fine for me.Ya you're right... stupid JBuilder failed me again; had to do a clean rebuild for JBuilder to recognize its not an error.

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Is this thread safe?

    I've got a HttpServletRequest instance variable in my servlet that I use in my model to retrieve parameters. The servlet looks like:
    public class MyServlet extends HttpServlet implements Controller {
      HttpServletRequest req;
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
      public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
      public void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.req = req;
        MyModel model = new MyModel(this);
        model.retrieve();
      public String getParameter(String parameter) {
        return req.getParameter(parameter);
    }The Controller interface has only one method - public String getParameter(String parameter)
    In MyModel because I pass an instance of Controller into the constructor I can do - controller.getParameter(parameter);
    Is what I'm doing thread safe?

    Actually, a static nested class is more appropriate than an inner class as there is no implicit outer-class reference to maintain:
    public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            processRequest(req, resp);
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            processRequest(req, resp);
        public void processRequest(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            MyModel model = new MyModel(new MyController(req));
            model.retrieve();
        private static class MyController implements Controller {
            private HttpServletRequest req;
            MyController(HttpServletRequest req) {
                this.req = req;
            public String getParameter(String parameter) {
                return req.getParameter(parameter);
    }This code is now thread safe because there is a different instance of MyController per thread. Note that if an instance of MyController is accessed by multiple threads, then its thread safety is dependent upon the thread safety of HttpServletRequest. However, based on the sort of thing I assume you are trying to do, I doubt you will be sharing instances between threads.

  • Questions concerning Nested Classes

    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?
    Thanks in advance,
    OIiver

    Trollhorn wrote:
    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
        private static class MyInner implements Runnable
            @Override public void run() // Must be public!
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?Wrong. It can define static final member variables and I see no reason to move them to the outer class, if they are used only by the inner class.
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?I agree with you here.
    Edited by: baftos on Jun 6, 2009 9:18 AM

  • JIT compiler and nested classes

    Q1. how does JIT compile on fly and improve the performance ?
    Q2. how is system.out.println(argument) implemented in java ? is it that system is a class in which out is a static nested class and println is a static method in out?

    Hello rishiluvsjava,
    Q1. How does JIT compile on fly and improve the performance?
    The following answer was taken from "The Java HotSpot Performance Engine Architecure: A White Paper About Sun's Second Generation Performance Technology" to view the full document go to:
    http://java.sun.com/products/hotspot/whitepaper.html
    Just-In-Time (JIT) compilers are essentially fast traditional compilers that translate the Java-technology bytecodes into native machine code on-the-fly. A JIT runs on the end-user's machine which actually executes the bytecodes, and compiles each method the first time it is executed.
    Q2. How is System.out.println(argument) implemented in java ? is it that system is a class in which out is a static nested class and println is a static method in out?
    From the Java docs:
    System is a public final class in the java.lang package. It has three fields:
    static PrintStream err    // The "standard" error output stream.
    static InputStream in    // The "standard" input stream.
    static PrintStream out  //The "standard" output stream.println is one of the methods in the java.io.PrintStream class.
    -Merwyn,
    Developer Technical Support,
    http://www.sun.com/developers/support.

  • Inner/Nested Classes

    Could someone tell me what the rules of accessibility are for static and non-static inner classes being able to access elements of the enclosing class

    A non-static or inner class can access all of the enclosing class's members, including private members. This is because each instance of an inner class is associated with an instance of the outer class, and inner classes are not allowed to have static members except for constants.
    A static nested class can access only the static members of the enclosing class. This is because instances of the nested class are not associated with instances of the outer class.

  • Is Servlet thread safe?

    Hi,
    I have created a application. All that the application does is that it listens at a predefined port say 8080 and for every request that is made to the application, the request header information is dumped into a file.
    I have implemented it by creating a servlet that implements the Filter interface and implemented its doFilter() method.
    In the method, I simply make use of the Servlet Request object and wite the header details in a file.
    The question : Is the above written Servlet class - thread safe?
    There are no class member variables defined.
    I have deployed the application on Tomcat 5.0.19.
    Regards,
    Montek Singh Ahluwalia

    Yes, Servlets are thread safe.
    Although it is standard to have one servlet instance per registered servlet name, it is possible for a servlet to elect instead to have a pool of instances created for each of its names, all sharing the duty of handling requests. Such servlets indicate this desire by implementing the javax.servlet.SingleThreadModel interface. This is an empty, tag interface that defines no methods or variables and serves only to flag the servlet as wanting the alternate life cycle.

  • Instantiating a nested class from JNI

    Im able to instantiate my public member class "Inner" as long as the constructor does not take any arguments. If it requires arguments in the constructor, I get a crash report. I need to be able to instantiate the object with supplied initial arguments. Is this a bug in the JVM? Any suggestions?
    /dan
    Crash report follows after code:
    class HelloWorld {
       public class Inner {
          private int myValue = 50;
          public Inner() {}
          public Inner(int myValue) {
             this.myValue = myValue;
          public Inner(int myValue, int there) {
             this.myValue = myValue;
    }C++ library:
       jclass inr_clz = env->FindClass("LHelloWorld$Inner;");
       if (inr_clz == NULL) {
          return -25;               // failed to find the class
    //   mid = env->GetMethodID(inr_clz, "<init>", "(LHelloWorld;)V");              // works
       mid = env->GetMethodID(inr_clz, "<init>", "(LHelloWorld;II)V");            // also works
       if (mid == NULL) {
          return -30;                    // failed to get method
       jint value = 400;
    //   inner = env->NewObject(inr_clz, mid);                           // works
       inner = env->NewObject(inr_clz, mid, value, value);             // crash here
       if (inner == NULL) {
          return -40;                     // out of memory error
       ...Crash message:
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # Internal Error (53484152454432554E54494D450E43505001A3), pid=2008, tid=2628
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode)
    # An error report file with more information is saved as hs_err_pid2008.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    #

    Im able to instantiate my public member class "Inner"
    as long as the constructor does not take any
    arguments. If it requires arguments in the
    constructor, I get a crash report. I need to be able
    to instantiate the object with supplied initial
    arguments. Is this a bug in the JVM? Any
    suggestions?It's your code.
    Here's a working example:
    ==================
    public class NativeInnerTest {
         public static void main(String[] args) {
              new Outer().doNative();
    public class Outer {
         static {
              System.loadLibrary("outer");
         public class Inner {
              private int val;
              Inner (int val) {
                   this.val = val;
              public void foo() {
                   System.out.println("Value is: " + val);
         public native void doNative();
    }=====Native Code======================
    #include "Outer.h"
    JNIEXPORT void JNICALL Java_Outer_doNative (JNIEnv *env, jobject obj) {
         jclass clz = env->FindClass("Outer$Inner");
         if (clz == NULL) {
              printf("Failed to find class Outer$Inner");
              return;
         jmethodID mid = env->GetMethodID(clz,"<init>", "(LOuter;I)V");
         if (mid == NULL) {
              printf ("Failed to find Inner constructor\n");
              return;
         jint val = 42;
         jobject inner = env->NewObject(clz,mid,obj,val);
         if (inner == NULL) {
              printf ("Failed to construct Inner object\n");
              return;
         jmethodID fooID = env->GetMethodID(clz, "foo", "()V");
         if (fooID ==  NULL) {
              printf ("Failed to find method id for foo()\n");
              return;
         env->CallVoidMethod(inner, fooID);
    }================================
    The problem in your code is twofold. First, your type signature in the call to GetMethodID is incorrect. An inner class constructor taking a single integer argument should have a type signature like this:
    (LHelloWorld;I)V
    You can get the proper type signatures using the 'javap' tool. For my example, the output of javap looks like this:
    [jim@daisy tmp]$ /usr/java/jdk1.6.0/bin/javap -s -private Outer.Inner
    Compiled from "Outer.java"
    public class Outer$Inner extends java.lang.Object{
    private int val;
      Signature: I
    final Outer this$0;
      Signature: LOuter;
    Outer$Inner(Outer, int);
      Signature: (LOuter;I)V
    public void foo();
      Signature: ()V
    }Second, your call to NewObject does not have the proper parameter types. Here's your code:
    inner = env->NewObject(inr_clz, mid, value, value);The corresponding correct line from my example is:
    jobject inner = env->NewObject(clz,mid,obj,val);The constructor expects a 'HelloWorld' object and an integer as denoted in the correct
    type signature.
    You are passing in the integer 'val' twice when you should be doing something like this:
    inner = env->NewObject(inr_clz, mid, obj, value);where 'obj' is the jobject passed to you by the VM along with the JNIEnv pointer. This jobject represents the instance of the enclosing class which every non static nested class must have.
    Jim S.

  • Static inner class

    class A{
    static class B{
    public void instanceMethod()
    System.out.println("instance method");
    class C{}How do I access the instanceMethod() of class B from class C ?

    But what does new A.B() mean.Static means that
    doesent run inside any instance of the class, rather it runs with class
    itself. So shouldnt it have been just A.new B()
    No, a static nested class is just a static member of the outer class.
    All other static members are accessible as Outer.innerMember and
    just so with that static nested class. Your proposal:A.new B()doesn't make sense because 'new' is not a static
    member of outer class A.
    kind regards,
    Jos

Maybe you are looking for