staitic variable to initiated only once
Hello, guys. I have a problem of static variables.
Suppose that I have a class B which contains a variable c which is an instance of class C
class B
{
static C c;
public B(int number)
{
/*Do something*/
}
privatevoid initC()
{
/** Does not work!!!!*/
if (c ==null)
c =new C();
}
}
and then B may be created for many times, but I just want B.c to be initiated only once.
publicclass A
{
publicstaticvoid main(String[] args)
{
int number = 10;
B[] b = B[number];
for (int i=0;i<number;i++)
{
b[i] =new B(i);
}
}
}
It could be the case that two Bs try to update c simutaniously, so I need some kind of synchronized method.
I am using Java 14.2, so no semaphore is provided, and I tried to create a semaphore by myself, and make that semaphore static, but again, it only reduces the chance, not solve that problem.
Can anybody give a hand? Thanks !!>
[2029 byte] By [
loudkinga] at [2007-10-2 22:13:28]

> Why don't you simply do this:> private static final C c= new C();
> nly when the class itself is loaded by a classloader
> the static
> variabe 'c' will be initialized.
>
> kind regards,
>
> Jos
Problem is I cannot d that because the constructor of C depends on some information of B, and it has to wait until B has been initiated.
That is the reason why I have to post this quetion here. :-(
> Problem is I cannot d that because the constructor of
> C depends on some information of B, and it has to
> wait until B has been initiated.
>
> That is the reason why I have to post this quetion
> here. :-(
When exactly do you execute the private init() method, in your code? Inside the constructor?
any B
> > Problem is I cannot d that because the constructor
> of
> > C depends on some information of B, and it has to
> > wait until B has been initiated.
>
> Which B? The first one to be instantiated?
>
> kind regards,
>
> Jos