Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of a Static Class?

I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same "instance" of that class?

Since the processes are separate, would these be running under difference Application Domains, hence have the static "instances" separate?

The pudding in the details here is that the assembly is being used by a custom BizTalk adapter that my be set to process the messages in parallel batches. That is what I am calling "multiple processes" above.

like image 352
Keith Sirmons Avatar asked Nov 12 '08 16:11

Keith Sirmons


People also ask

What is the scope of static class in Java?

In particular, static variables are perfectly usable without any instances being created. That gives a clue as to the scope of statics: they're scoped by the Class object representing the containing class, which is in turn scoped by the ClassLoader that loaded it.

What is the scope of static method?

static: The scope of the method is made to be static which means that all the member variables and the return type will be within the scope of static. void: This keyword in the syntax flow represents that there is no return type handled in the current method.

What is a static class?

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.

Does a static field have global scope?

The scope of a static is global - within its owning classloader. A JVM can create multiple classloaders and load separate instances of your class in each of new classloaders. Statics are not global per JVM, they are global per classloader.


2 Answers

Static classes exist once per application domain. In your case, it would depend on whether the adapter is using multiple threads in the same application domain (thus sharing a single instance of the static class) or using multiple processes (thus having separate instances of the static class).

like image 104
tvanfosson Avatar answered Sep 28 '22 16:09

tvanfosson


Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (Monitor or lock your properties).

However, multiple processes should be in separate AppDomains and therefore each have their own instance.

like image 41
Joel Coehoorn Avatar answered Sep 28 '22 14:09

Joel Coehoorn