A way to have some code run once at the initialization of a worker is to use a hook, that you define in the configuration before submitting the topology.
conf.put(Config.TOPOLOGY_AUTO_TASK_HOOKS, Arrays.asList(MyHook.class.getName())); Then the "prepare" method of the hook will be called once per worker before any bolt or spout. That said, if you want a singleton, in Java, a proper way is to use an enum singleton (http://stackoverflow.com/a/71399/39622) 2014-11-05 7:46 GMT-05:00 Nathan Leung <[email protected]>: > If you initialize in prepare at least you don't have to check it every > time you access it. > On Nov 5, 2014 7:09 AM, "Alex Zuzin" <[email protected]> wrote: > >> A lazy init singleton is precisely what I'm trying to avoid. I guess I >> can't, huh. >> >> Sent from my iPhone >> >> On Nov 5, 2014, at 14:57, Nathan Leung <[email protected]> wrote: >> >> Once per task. I use static fields in the class and check the field >> during prepare (with proper synchronization of course). Or a static field >> with static initialization. I guess this might not work entirely as you >> expect if you have multiple classloaders loading your bolt class. >> On Nov 5, 2014 6:32 AM, "Alex Zuzin" <[email protected]> wrote: >> >>> Do I understand correctly that bolts are instantiated once per worker >>> and never re-prepared? >>> >>> Thank you, >>> - alexz >>> >>> Sent from my iPhone >>> >>> On Nov 5, 2014, at 13:37, Itai Frenkel <[email protected]> wrote: >>> >>> AFAIK submitTopology submits the JAR to Nimbus which is then loaded to >>> each worker, so it is run only once, and not on each worker. >>> >>> >>> We use a dummy bolt's prepare method for that. Not sure what is the >>> "correct" way of doing it. >>> >>> >>> Itai >>> ------------------------------ >>> *From:* Alex Zuzin <[email protected]> >>> *Sent:* Wednesday, November 5, 2014 10:43 AM >>> *To:* [email protected] >>> *Subject:* Once-per JVM init? >>> >>> Hi all! >>> >>> Am I correct to assume that "submitTopology" is executed once per JVM >>> and is a good place to init resources that require once-per-JVM >>> initialization? >>> If not, is there such a spot (it needs to have access to Storm config)? >>> If yes, where? :) >>> >>> Thank you! >>> >>> -- >>> "If you can't conceal it seamlessly, expose it vigorously" >>> >>> -- Cyrille Karmann +1-514-659-1209 [email protected]
