Jim H
Jim H
  • Home
  • Resume
  • Code Review-BestPractices
  • Java Best Practices
  • Kotlin Best Practices
  • Homophones in English
  • Personal
  • Blog

Appendix: Code Snippets

Back to Contents


SpringContext

15-Minute Boundaries

CountOnes

SpringContext

A Spring component that allows non-components to load beans; SpringContext implements ApplicationContextAware to get the context, then implements a static method to allow loading a bean.


import org.jetbrains.annotations.NotNull;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext; 

import org.springframework.context.ApplicationContextAware; 

import org.springframework.stereotype.Component; 


/**

  * Component that allows non-components to find and use beans.

  * Credit:  Jay Ta'ala  * @see <a href="https://me.jaytaala.com/super-simple-approach-to-accessing-spring-beans-from-non-spring-managed-classes-and-pojos/">

  *     this KB post</a>  */ 

@Component 

public class SpringContext implements ApplicationContextAware {

  private static ApplicationContext context;


      /**

    * Get a bean of the given class.

    *

    * @param beanClass class object

    * @param <T> bean type

    * @return bean    */

  public static <T> T getBean(Class<T> beanClass) {

      return context.getBean(beanClass);

  }


      /**

    * Sets the application context on startup.

    *

    * @param applicationContext  context

    * @throws BeansException on error

    */

  @Override

  public void setApplicationContext(@NotNull ApplicationContext applicationContext)  throws BeansException {

     context = applicationContext;

  } 

}

Temporal Objects: 15-Minute Boundary

Get the beginning boundary of the current 15-minute period. If we hit the 1-in-900,000 chance of timestamp being at the starting millisecond of the period, back up to the previous period.


@NotNull

public static ZonedDateTime boundary15Minutes(@NotNull String timestamp) {

  Matcher matcher = MILLIS_PATTERN.matcher(timestamp);

  ZonedDateTime time;

  if (matcher.matches()) {

    Instant instant = Instant.ofEpochMilli(Long.parseLong(timestamp));

    time = ZonedDateTime.ofInstant(instant, UTC);    

  } else {

    time = parseDate(timestamp);  

  }  

  int minute = (time.getMinute() / 15) * 15;  

  ZonedDateTime tTime = time.truncatedTo(ChronoUnit.HOURS)

        .plusMinutes(minute);  

  if (tTime.isEqual(time)) {       

    tTime = tTime.minusMinutes(15);  

  }  

  return tTime;  

}

Temporal Objects: Multiple 15-Minute Boundaries

Get the time in 15-minute windows bounded by start & end times.

@NotNull 

public static Pair<ZonedDateTime, ZonedDateTime>  

    truncatedInterval(@Nullable String start, 

                      @Nullable String end) {

  if (start == null) {       

    start = Long.toString(System.currentTimeMillis());  

  }  

  ZonedDateTime startTime = boundary15Minutes(start);  

  ZonedDateTime endTime;  

  if (end == null) {       

    endTime = startTime.plusMinutes(15);  

  } else {       

    endTime = boundary15Minutes(end);  

  }  

  return new ImmutablePair<>(startTime, endTime);  

}

Instead of ZonedDateTime, these could be rewritten in terms of Instant, OffsetDateTime, or any other implementor of Temporal.

Count One Bits

Count the number of 1 bits in a long. (Note: this does not assume any value for the number of bits in a long; it is therefore adaptable to any language on any architecture.)


The "Correct" (but un-optimized) Solution

public int countOnesCorrect(long value) {

    int ones = 0;

    while (value != 0) {

        if ((value & 1) != 0) {

            ones++;

        }

        value >>>= 1;   // logical (0-filling) shift

    }

    return ones;

}

This method tests each bit, and increments the counter if it's a 1.


A Faster Method: Count Multiple Bits at Once

public int countOnesFaster(long value) {

    int ones = 0;

    while (value != 0) {

        switch (value & 0x0F) { // 4 lowest bits (1 nybble)

        case 0:    // no 1 bits in nybble

            break;

        case 1:    // one 1 bit in nybble

        case 2:

        case 4:

        case 8:

            ones += 1;

            break;

        case 3:    // two 1 bits in nybble

        case 5:

        case 6:

        case 9:

        case 0xA:

        case 0xC:

            ones += 2;

            break;

        case 7:    // three 1 bits in nybble

        case 0xB:

        case 0xD:

        case 0xE:

            ones += 3;

            break;

        case 0xF: // four 1 bits in nybble

            ones += 4;

            break;

        }

        value >>>= 4; // load next 4 bits

    }

    return ones;

}

Same as the previous method, except bits are tested 4 at a time.


Unlike the methods above, this one does make an assumption: that it is running on a Two's Complement architecture. (Always true for Java, usually true on modern hardware.)

The Fastest way: Use a Quirk of Two's Complement Arithmetic

public int countOnesFastest(long value) {

    int ones = 0;

    while (value != 0) {

        value -= value & -value;  // zero out rightmost 1 bit

        ones++;

    }

    return ones;

}

Here, no bits are "tested." Instead, remember that the Two's Complement of a number is identical to the number from the least significant bit through the rightmost 1 bit. Therefore, the logical AND of a number with its Two's Complement is just the rightmost 1 bit. This method executes the loop once per 1 bit in the original value. On average, it's nearly twice as fast as the "Correct" version above; in the worst case (value == -1), it's slower; in the best case (value == 0) it's lightning fast.

Buttons

First PagePreviousHome

Copyright © 2019-2025 Jim Hamilton - All Rights Reserved.

Powered by

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

DeclineAccept