Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Cecil Westerhof Newsgroups: comp.lang.java.programmer Subject: Re: Logging database statement duration in a DRY way Date: Fri, 19 Aug 2016 20:54:45 +0200 Organization: Decebal Computing Lines: 46 Message-ID: <87lgzsio7e.fsf@Equus.decebal.nl> References: <87wpjdhrbm.fsf@Equus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="12baf5125b19322b899c79c2e3878015"; logging-data="6546"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19VRIw2Pzor1PmRu5FaNVpMtdCpl7xBmzQ=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) X-Homepage: http://www.decebal.nl/ Cancel-Lock: sha1:zaXBhq5RVHnuSrSO95rLWkbsEUs= sha1:xMFet7cLmAsZ9++bxPRaVKpKG98= Xref: csiph.com comp.lang.java.programmer:35418 On Friday 19 Aug 2016 15:05 CEST, Eric Sosman wrote: > On 8/19/2016 8:32 AM, Cecil Westerhof wrote: >> I like to log the time it takes for certain database actions. At >> the moment I do this like this: startTime = System.nanoTime(); ps = >> conn.prepareStatement(insertLine); ps.setString(1, className); >> ps.setLong( 2, pid); ps.setLong( 3, free); ps.setLong( 4, >> rt.maxMemory() / divideValue); ps.setLong( 5, total); >> ps.executeUpdate(); ps.close(); stopTime = System.nanoTime(); >> logMessage(String.format("preparedStatement saveMemoryLineNoGC took >> %f milliseconds", (stopTime - startTime) * 1E-6)); >> >> This works, but I need to copy the first and last two statements >> and edit the last one, so I was wondering if this could be done >> more DRY (Do not Repeat Yourself). In C(++) you would use a macro, >> but as far as I know this is not possible with Java. > > I suppose you could put the "guts" in an instance implementing a > suitable interface and hand the instance to a time-it-and-log-it > method. You might end up with something like > > static void timeAndLog(String label, Runnable thing) { > long startTime = System.nanoTime(); > thing.run(); > long stopTime = System.nanoTime(); > logMessage(String.format("%s took %f milliseconds", > (stopTime - startTime) * 1E-6); > } > > // ... > > timeAndLog("preparedStatement saveMemoryLineNoGC", () -> { > ps = conn.prepareStatement(insertLine); > // ... > ps.close(); > }); > > Only you can judge whether this is worth while. I already found a solution. (See my reply on my own post.) For the moment that is good enough, but I will keep your solution in mind. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof