|
|
| Petterson Mikael 2007-06-21, 8:09 am |
| Hi,
I have seeen the following in java class:
public class MyClass {
static {
try{
}catch(Exception e){
}
}
synchronized public static MyClass instance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
}
1. What is the interpretation of static { } ?
2. What is the interpretation of 'synchronized public static MyClass
instance()'?
cheers,
//mikael
| |
| Ingo R. Homann 2007-06-21, 8:09 am |
| Hi,
Petterson Mikael wrote:
> public class MyClass {
>
>
> static {
>
> try{
>
> }catch(Exception e){
>
>
> }
>
> }
>
>
> synchronized public static MyClass instance() {
> if (instance == null) {
> instance = new MyClass();
> }
>
> return instance;
> }
>
>
>
>
>
> }
>
> 1. What is the interpretation of static { } ?
It is the "static initializer" which is executed when the class is loaded.
> 2. What is the interpretation of 'synchronized public static MyClass
> instance()'?
What exactly is the point you do not understand?
Ciao,
Ingo
| |
| Petterson Mikael 2007-06-21, 8:09 am |
| Ingo R. Homann wrote:
> Hi,
>
> Petterson Mikael wrote:
>
>
>
> It is the "static initializer" which is executed when the class is loaded.
When will it be loaded?
>
Is this a singleton to make sure I only have one instance of this class?
Why would I make it synchronized?
cheers,
//mikael
[color=darkred]
>
>
> What exactly is the point you do not understand?
>
> Ciao,
> Ingo
>
| |
| Roedy Green 2007-06-21, 8:09 am |
| On Thu, 21 Jun 2007 09:42:45 +0200, Petterson Mikael
<mikael@no.reply.to.se> wrote, quoted or indirectly quoted someone who
said :
>
>1. What is the interpretation of static { } ?
see http://mindprod.com/jgloss/staticinit.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
| |
| Roedy Green 2007-06-21, 8:09 am |
| On Thu, 21 Jun 2007 09:42:45 +0200, Petterson Mikael
<mikael@no.reply.to.se> wrote, quoted or indirectly quoted someone who
said :
>2. What is the interpretation of 'synchronized public static MyClass
>instance()'?
see http://mindprod.com/jgloss/synchronized.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
| |
| Ingo R. Homann 2007-06-21, 8:09 am |
| Hi,
Petterson Mikael wrote:
>
> When will it be loaded?
When the it is "used" the first time. (Note that e.g. a simple 'import'
does not mean that the class is used.)
See the langspec if you need more precise information (which should not
be necessary).
>
> Is this a singleton to make sure I only have one instance of this class?
The implementation suggests that it is a singleton, indeed.
But I thought you had problems with the declaration, not with the
implementation?
Which of the parts do you have problems with?:
- synchronized
- public
- static
- "MyClass"
- "instance"
- Braces ()
> Why would I make it synchronized?
Ever heard of "multi-threading"? If not, then read a good book or
tutorial (e.g. see Roedys hint).
Ciao,
Ingo
| |
|
|
|
|
|
|
|
|