Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #34450
| From | Marcel Mueller <news.5.maazl@spamgourmet.org> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: enums and static init |
| Date | 2016-06-03 08:02 +0200 |
| Organization | MB-NET.NET for Open-News-Network e.V. |
| Message-ID | <nir6kv$j13$1@gwaiyur.mb-net.net> (permalink) |
| References | <3e42lbtors5agrp11jkdsmjbfs2pcp64h0@4ax.com> |
On 03.06.16 07.15, Roedy Green wrote: > I had a static init section that allocated and used some enums from > another class. When I ran it, I got a null pointer exception in the > enum class. > > I converted the static init into a static method, and did a lazy init. > It worked fine -- the same init code. > > Has anyone ever seen behaviour similar to this? There is no well defined sequence of static initializers in all cases. As soon as they have cyclic dependencies things become unreliable. In this case a well defined, custom initialization sequence should be preferred. Lazy init is one option. But is has drawbacks too. First of all the class loader does already lazy init. So your lazy init is probably just a bit 'lazier'. But lazy init still cannot handle cyclic references and it might cause a runtime overhead by checking for (zillions of) is_initialized flags all the time. Furthermore you need to be aware of threading issues. So either you need to synchronize the check - now it /is/ a considerable runtime overhead - or by using memory barriers and the double check idiom. At the end it might be more reasonable to provide a custom initialization function for classes that need to be initialized. Because of the lazy class loader the class cannot register this function automatically at some init provider. You need to call init explicitly from a global ensure_init function (e.g. for an entire library). This might call further ensure_init for it's dependencies first. In fact this is also some kind of lazy init but now you are safe with respect to threading issues as long as you do not call the top level init from multi-threaded context and once initialized there is no more runtime overhead. To speed up program load you might run some entirely independent initialization blocks in parallel if required. Static initialization is always subject to problems, even in languages automatic lazy class loading like Java and .NET. In most cases cyclic references are the problem. They might not be obvious at the first glance. Place a break point into the static constructors of both related classes to examine the call stacks. Marcel
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Find similar | Unroll thread
enums and static init Roedy Green <inquiry@mindprod.com> - 2016-06-02 22:15 -0700 Re: enums and static init Marcel Mueller <news.5.maazl@spamgourmet.org> - 2016-06-03 08:02 +0200
csiph-web