Troubling yet Good News from GitHub

Link

GitHub has been scanning source code for some time now for API tokens.  The troubling part is that they have found one billion tokens locked in the collective source code.  What is good about it is that GitHub partners get notified so the exposed tokens are removed from circulation and prevents more break-ins.  I have gotten one of these messages from stupid mistakes I have done and they are very professional and not judgmental at all.  It made me think about my software design and how I can make it more secure.

Keys are tied to users, this means that the developer or organization could get into trouble and not the hacker.  I would rather not have conversations with the authorities over something this simple to prevent.

For more information on the program, click the link below.

GitHub Token Scanning—one billion tokens identified and five new partners

Advertisements

Dusting Off the Secret Hideout

Standard

Beginnings are the Hardest

Beginnings are the hardest for me, because they set the tone for what is going to come. That is why I don’t introduce myself as a technical person when I first meet someone. I want them to know me as a person that can be technical rather than a technical person. That way I don’t get, “Can you fix my computer?”

The middle is easier because the tone is set and the subject is set.  Just follow the beginning and rest almost writes itself.

The ending can be the easiest of all. What can be said is said, complementing the beginning. Endings are hardest when the middle is not finished.

What is This?

I have been known to write an article not about Java development, but about soft skills needed to exist in the software development realm. This is a professional blog.

There have been personal events in my life that cause the line of personal and professional sides to blur. I am in one of those times. I recently had a loss in my family and it is causing me to reassess everything, and I mean everything, even this blog. I am exploring everything that I have done and things that are new.

I remember enjoying writing and want to see if I still want to do it.  I don’t even know if this post will see the light of day.  After four strong yeses to post this, it has been posted.

I felt like I was giving back to the open source community that has provided so much help in solving problems, from infrastructure like OSes and tools like Maven to code snippets.

I am dusting off the equipment of the secret hideout and seeing if the tires are still good, the lights turn on and if the door even opens.

What has Changed

I look different now, I need to update my picture.  I am surrounding myself with creative and technical people who have no filter.  I know exactly where I am with them.  I feel like I have lost everything so I have nothing to lose.  I am realizing that I creative too and have been my whole life.

What has not Changed

I am still a person who happens to be technical.  I still create whether I recognize that or not.  I still love my friends and family.

What will Change

If this blog continues, it will be about solving problems through technical means.  That solution may not be with Java, so the title will change to reflect that.  It will go further in depth of why I chose the design path I chose.  Sometimes explaining why I chose that path can be more helpful than the code itself.

Endings are the Easiest

This is an exploration of if I want to keep writing.  Several people will read this to see if it is even appropriate to publish.  In the end, I will continue relearning about myself no matter if I continue a blog or not.

DIY Annotations

Standard

Since Java 5 there have been annotations in Java.  I wanted to make my own annotation just to see what it takes.  However, I found out that they were just interfaces.

There is the rub

Interfaces have no teeth behind them.  Some piece of code has to implement it.  I figured this is where the rubber hits the road and I really find a way to do this.

To start, I would need a purpose

I picked one recent hot topic, caching.  I didn’t want to implement JSR 109(JCache) but I didn’t want to do the typical “Hello World” either.  I picked implementing two annotations, one without any parameters and one with a parameter.  I also needed a caching provider.  Might as well bring a real caching library to the mix if I am going to do this.  It also follows my design philosophy to use products/libraries to reach  a goal instead of home spinning everything.  After careful consideration, I chose hazelcast to be my caching engine.  It is the fastest on the market and it is free.

More Decisions

After my purpose was chosen, I still needed to find out how to put teeth behind them.  After some digging around I found two methods:

Reflection

Almost every time I have used reflection, I have felt sorry for making such a clunky piece of code.  Plus, to do it the way I would like, I would have to create my own framework.  Sounds like a lot of work for two annotations.

Aspect Oriented Programming(AOP)

This was a perfect fit for what I wanted to do.  AOP deals in reducing boilerplate code into a single place.  This would be convenient and dovetails into caching because caching breaks down into the following steps:

  1. Check to see if this situation was done before.
  2. If so:
    1. retrieve the stored result
  3. if not:
    1. run the function
    2. store the result
  4. return the result

That maybe an oversimplification but in a nut shell it is true.  Like in all things, the devil is in the details.

Meanwhile, Back at the AOP Ranch

While I knew AOP was the place for me, I did not know much about it.  I found that Spring has an AOP library and that a well known library is AspectJ.  AspectJ is unfamiliar to me and needs a runtime engine to work.  I am much more familiar with Spring so I picked it.  As I dug into Spring’s AOP, I found that I had to delve into AspectJ’s annotations so I was stuck with AspectJ in some form or fashion anyway.

New Concepts, New Vocabulary

Writing aspects aren’t like writing objects.  They are objects but not really so, of course, a new set of terms are needed.  The ones I used are in the Spring AOP Documentation

I really needed to read the page a couple of times to grasp what is being said.  One is highly recommended to do the same or the rest of the post is going to sound like gibberish.

What Makes the Pointcut and How to Advise it

The pointcut design was easy since I was only interested in methods that had the annotation.  The advise it needed was the around advice because I needed to be able to circumvent calling the method if there was a matching call already done.

Finally the Code

Maven Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.darylmathison</groupId>
    <artifactId>annotation-implementation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>

    <description>
        This project is an example of how to implement an annotation via Spring AOP.
    </description>

    <scm>
        <url>https://github.com/darylmathison/annotation-implementation-example.git</url>
        <connection>scm:git:https://github.com/darylmathison/annotation-implementation-example.git</connection>
        <developerConnection>scm:git:git@github.com:darylmathison/annotation-implementation-example.git</developerConnection>
    </scm>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/darylmathison/annotation-implementation-example/issues</url>
    </issueManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.8</version>
        </dependency>

        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.7</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>dependencies</report>
                            <report>index</report>
                            <report>project-team</report>
                            <report>issue-tracking</report>
                            <report>scm</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>2.18.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>javadoc</report>
                            <report>test-javadoc</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <linkJavadoc>true</linkJavadoc>
                </configuration>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>jxr</report>
                            <report>test-jxr</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-changelog-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <type>range</type>
                    <range>90</range>
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</project>

The Annotations

CacheMe

Cute name for a caching annotation, right?

package com.darylmathison.ai.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by Daryl on 2/19/2016.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CacheMe {
}

CacheMeNow

package com.darylmathison.ai.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by Daryl on 2/19/2016.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CacheMeNow {
    String key();
}

Spring Configuration

I decided to use Java based configuration instead of XML like I normally use for a change of pace. The EnableAspectJAutoProxy annotation is key to getting Spring AOP to start working. I was beside myself until I read this about this little jewel. Sometimes it is the easiest thing that burns a day.

AppConfig

package com.darylmathison.ai.config;

import com.darylmathison.ai.cache.CacheAspect;
import com.darylmathison.ai.service.FibonacciService;
import com.darylmathison.ai.service.FibonacciServiceImpl;
import com.hazelcast.config.Config;
import com.hazelcast.config.EvictionPolicy;
import com.hazelcast.config.MapConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Daryl on 2/20/2016.
 */
@Configuration
@ComponentScan(basePackages = "com.darylmathison.ai")
@EnableAspectJAutoProxy
public class AppConfig {

    @Bean
    public Map<String, Object> cache() {
        Config config = new Config();
        MapConfig mapConfig = new MapConfig();
        mapConfig.setEvictionPercentage(50);
        mapConfig.setEvictionPolicy(EvictionPolicy.LFU);
        mapConfig.setTimeToLiveSeconds(300);
        Map<String, MapConfig> mapConfigMap = new HashMap<>();
        mapConfigMap.put("cache", mapConfig);
        config.setMapConfigs(mapConfigMap);

        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
        return instance.getMap("cache");
    }

    @Bean
    public FibonacciService fibonacci() {
        return new FibonacciServiceImpl();
    }

    @Bean
    public CacheAspect cacheAspect() {
        return new CacheAspect();
    }
}

Service Code

Classic Spring based design needs a service right? Because Spring uses proxies to implement their AOP, it is highly advised to define an interface for the annotated class to implement.

FibonacciService

package com.darylmathison.ai.service;

/**
 * Created by Daryl on 2/20/2016.
 */
public interface FibonacciService {

    long calculate(int rounds);

    long calculateWithKey(int rounds);
}

FibonacciServiceImpl

package com.darylmathison.ai.service;


import com.darylmathison.ai.annotation.CacheMe;
import com.darylmathison.ai.annotation.CacheMeNow;

/**
 * Created by Daryl on 2/20/2016.
 */
public class FibonacciServiceImpl implements FibonacciService {

    @Override
    @CacheMe
    public long calculate(int rounds) {
        return sharedCalculate(rounds);
    }

    @Override
    @CacheMeNow(key = "now")
    public long calculateWithKey(int rounds) {
        return sharedCalculate(rounds);
    }

    private static long sharedCalculate(int rounds) {
        long[] lastTwo = new long[] {1, 1};

        for(int i = 0; i < rounds; i++) {
            long last = lastTwo[1];
            lastTwo[1] = lastTwo[0] + lastTwo[1];
            lastTwo[0] = last;
        }

        return lastTwo[1];
    }
}

AOP Stuff

This is heart of the annotation implementation. Everything else is support to do the source that follows.

SystemArch

According to Spring documentation, centralizing the pointcut definitions are a good idea.

package com.darylmathison.ai.cache;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * Created by Daryl on 2/20/2016.
 */
@Aspect
public class SystemArch {

    @Pointcut("@annotation(com.darylmathison.ai.annotation.CacheMe)")
    public void cacheMeCut() {

    }

    @Pointcut("@annotation(com.darylmathison.ai.annotation.CacheMeNow)")
    public void cacheMeNowCut() {

    }
}

CacheAspect

The Around annotations take the full method names of the pointcut class to define what to advise. The advice for the CacheMeNow annotation includes an extra condition so the annotation can be defined so the key parameter can be read. There is a design bug in CacheMeNow that is revealed in the test code.

package com.darylmathison.ai.cache;

import com.darylmathison.ai.annotation.CacheMeNow;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Created by Daryl on 2/20/2016.
 */
@Aspect
public class CacheAspect {

    @Autowired
    private Map<String, Object> cache;

    @Around("com.darylmathison.ai.cache.SystemArch.cacheMeCut()")
    public Object simpleCache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StringBuffer keyBuffer = new StringBuffer();
        for(Object o: proceedingJoinPoint.getArgs()) {
            keyBuffer.append(o.hashCode());
        }
        String key = keyBuffer.toString();
        Object ret = cache.get(key);
        if(ret == null) {
            ret = proceedingJoinPoint.proceed();
            cache.put(key, ret);
        }
        return ret;
    }

    @Around("com.darylmathison.ai.cache.SystemArch.cacheMeNowCut() && @annotation(cacheMeNow)")
    public Object simpleCacheWithParam(ProceedingJoinPoint proceedingJoinPoint, CacheMeNow cacheMeNow) throws Throwable {
        Object ret = cache.get(cacheMeNow.key());
        if(ret == null) {
            ret = proceedingJoinPoint.proceed();
            cache.put(cacheMeNow.key(), ret);
        }
        return ret;
    }
}

Test Code

Driver code to show that the annotations do cause caching.

FibonacciTest

package com.darylmathison.ai.service;

import com.darylmathison.ai.config.AppConfig;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by Daryl on 2/20/2016.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class FibonacciTest {

    private static final int ROUNDS = 12;
    private static final long ANSWER = 377;

    @Autowired
    private FibonacciService fibonacci;

    @org.junit.Test
    public void testCalculate() throws Exception {
        long start = System.currentTimeMillis();
        Assert.assertEquals(ANSWER, fibonacci.calculate(ROUNDS));
        long middle = System.currentTimeMillis();
        Assert.assertEquals(ANSWER, fibonacci.calculate(ROUNDS));
        long end = System.currentTimeMillis();
        Assert.assertTrue((end - middle) < (middle - start));
    }

    @org.junit.Test
    public void testCalculateWithKey() throws Exception {
        Assert.assertEquals(ANSWER, fibonacci.calculateWithKey(ROUNDS));
        // This test should not pass
        Assert.assertEquals(ANSWER, fibonacci.calculateWithKey(13));
    }
}

Conclusion

Annotations do not have to be hard to implement. Using AOP programming, I was able to implement two annotations with little coding.  The code can be found here.

The One Thing They Should have Taught in School

Standard

One of the reasons I got into computers is because computers are not people.  The other reason is that life was boring and computers are challenging.  Part of the reason I got through college is because I was around people that understood computers better than I and I could learn from them.  As I have matured in my career I have found one glaring and now obvious fact that I wish was pounded into me during college.  It was indirectly taught with core classes but I needed a literal tell me straight statement.  If could talk to my former, younger self, here is what would I say.

Computers and People Coexist

You cannot get away from people no matter hard one tries.  One can surround themselves with computers and screens and it will not make a difference.  Any project worth doing nowadays is usually done in a team.  This means meetings, asking and answering questions and if one is blessed, training and mentoring.

The Ultimate User is a Person

After all the fancy multi-tiered design, implementation and the various types of testing done, that project will have a human in the loop making decisions and inputting data.  That means requirements come from … humans because humans are going to use it.  Requirements require understanding.  Understanding requires questions.  Questions require answers.  Question and answers require a time and place to ask and receive information.  Assigning a time and place to gather information is a meeting.  Meetings require people.

Teams Require People to Function

Teams are split up into areas of expertise.  These experts need each other to reach the same goal.  Reaching that goal requires communication.  Communication typically requires people.

Want a Job?

To become a professional software developer, one needs employment.  To become employed, one needs an interview.  Interviews are conversations convincing another human being about how much an expert one is.  One of the interviewer’s jobs is to convince that the candidate should work for the employer he/she represents.  Selling yourself means knowing a particular type of communication.  Communication could be between computers but not in an interview.  Interviews require people interacting.

Networking

I cannot tell one how many jobs I have landed because someone recommended me.  That is because I got my head out of the computer and talked computers with a teammate, enough said.

Well, There it is

That is what I would have told my college self if I could.

Beginner’s Guide to Hazelcast Part 7

Standard

This is a continuation of a series explaining how to use Hazelcast.  If one has not read the other six posts, please go to the Table Of Contents and read the other posts.

A Different Breed of Map

Hazelcast’s MultiMap breaks the normal mold of using java.util.Collection interfaces that have been used in former posts.  In fact, the concept of a MultiMap breaks the idea of a map altogether in my opinion.  While normal maps associate one key to one value, MultiMaps can map multiple values to the same key.  That is a really important concept, multiple values to the same key.  Values can be stored in two different collections, set or list.  These collections act like the collections of java.util.Collections library.

Is it Safe?

MultiMaps have a method to their madness.  In a normal map, multiple values per key can be stored but it has to be done manually.  That means getting a collection out of storage, doing any changes and then putting the collection back into storage.  This can be problematic for thread safety because the prior steps need to be done atomically or there is the possibility of stale or inconsistent data being read by other threads.  MultiMaps help with this problem by offering the following services:

  • One can add a value via a single put operation.
  • One can lock an entry by the key.  This is key (pun intended) because this means the developer does not have to keep track of a separate lock per entry.

Example

This example is a little different because I used Maven’s failsafe plugin as the main engine when running the examples.  Yes, I wrote two examples because I wanted to show two different ways of using a MultiMap.  One way is every thread getting their own playground, being assigned an unique key, or being assigned a shared playground or all of the threads sharing the same key.  This also is an example of how Hazelcast’s IdGenerator can be used as a method of creating thread safety in an application.

Pom File

Remember, this example code takes advantage of Apache’s Failsafe Maven plugin.  The failsafe plugin aids in automated integration tests by not killing the build at the first failure.  It is a fork of the surefire plugin.  I also have been experimenting with the reporting that is available with Maven.  Type “mvn site” at the command line and it will generate a website.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0>

    <groupId>com.darylmathison>
    <artifactId>hazelcast-multimap-example>
    <version>1.0-SNAPSHOT>
    <description>Examples of using Hazelcast Multimap>
    <developers>
        <developer>
            <name>Daryl Mathison>
            <id>dmathison>
            <roles>
                <role>developer>
            >
        >
    >

    <scm>
        <connection>scm:git:https://github.com/darylmathison/hazelcast-multimap-example.git>
        <url>https://github.com/darylmathison/hazelcast-multimap-example>
    >

    <properties>
        <maven.compiler.source>1.8>
        <maven.compiler.target>1.8>
        <project.build.sourceEncoding>UTF-8>
    >

    <dependencies>
        <dependency>
            <groupId>com.hazelcast>
            <artifactId>hazelcast>
            <version>3.4.2>
        >
        <dependency>
            <groupId>junit>
            <artifactId>junit>
            <version>4.12>
            <scope>test>
        >
    >

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins>
                <artifactId>maven-failsafe-plugin>
                <version>2.18.1>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test>
                            <goal>verify>
                        >
                    >
                >
            >
        >
    >

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins>
                <artifactId>maven-project-info-reports-plugin>
                <version>2.7>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>dependencies>
                            <report>index>
                            <report>project-team>
                            <report>scm>
                        >
                    >
                >
            >
            <plugin>
                <groupId>org.apache.maven.plugins>
                <artifactId>maven-javadoc-plugin>
                <version>2.10.3>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>javadoc>
                            <report>test-javadoc>
                        >
                    >
                >
            >
            <plugin>
                <groupId>org.apache.maven.plugins>
                <artifactId>maven-surefire-report-plugin>
                <version>2.18.1>
            >
            <plugin>
                <groupId>org.apache.maven.plugins>
                <artifactId>maven-jxr-plugin>
                <version>2.5>
                <configuration>
                    <linkJavadoc>true>
                >
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>jxr>
                            <report>test-jxr>
                        >
                    >
                >
            >
        >
    >
>

MultimapAccessThread

This is the base class for each of the access type threads.

package com.darylmathison.multimap;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.core.MultiMap;

import java.io.Serializable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Abstract class to access MultiMap.
 */
public abstract class MultiMapAccessThread implements Serializable, Runnable, HazelcastInstanceAware {
    protected com.hazelcast.core.HazelcastInstance instance;
    protected MultiMap<Long, Long> map;
    protected String mapName;
    protected Lock l = new ReentrantLock();

    public void setHazelcastInstance(HazelcastInstance instance) {
        l.lock();
        try {
            this.instance = instance;
            if (mapName != null && !mapName.isEmpty()) {
                map = instance.getMultiMap(mapName);
            }
        } finally {
            l.unlock();
        }
    }

    public String getMapName() {
        return mapName;
    }

    public void setMapName(String mapName) {
        l.lock();
        try {
            this.mapName = mapName;
        } finally {
            l.unlock();
        }
    }
}

IdMultiMapAccessThread

package com.darylmathison.multimap;

/**
 * This thread accesses only one "slot" in a multimap.
 */
public class IdMultiMapAccessThread extends MultiMapAccessThread {
    private Long id;

    @Override
    public void run() {
        l.lock();
        boolean shouldRun = (map != null && id != null);
        l.unlock();
        if(shouldRun) {
            for (long i = 0; i < 10; i++) {
                map.put(id, i);
            }
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

GroupMultiMapAccessThread

package com.darylmathison.multimap;

/**
 * Thread designed to share the same "slot" on a MultiMap.
 */
public class GroupMultiMapAccessThread extends MultiMapAccessThread {

    private static final long MAX = 10;

    private Long groupId;

    /**
     * When an object implementing interface Runnable is used
     * to create a thread, starting the thread causes the object's
     * run method to be called in that separately executing
     * thread.
     * 
     * The general contract of the method run is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        l.lock();
        boolean shouldRun = (groupId != null && map != null);
        l.unlock();
        if(shouldRun) {
            map.lock(groupId);
            try {
                if (map.get(groupId).isEmpty()) {
                    System.out.println("adding to list");
                    for (long i = 0; i < MAX; i++) {
                        map.put(groupId, i);
                    }
                } else {
                    System.out.println("nothing to add");
                }
            } finally {
                map.unlock(groupId);
            }
        }
    }

    public void setGroupId(Long groupId) {
        l.lock();
        this.groupId = groupId;
        l.unlock();
    }
}

HazelcastInstanceResource

This rule starts up and shuts down the Hazelcast instance needed for running the threads.

package com.darylmathison.multimap.test.rule;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IExecutorService;
import org.junit.rules.ExternalResource;

/**
 * Created by Daryl on 4/27/2015.
 */
public class HazelcastInstanceResource extends ExternalResource {
    public static final String SERVICE_NAME = "Charlotte";
    HazelcastInstance instance;
    IExecutorService service;

    @Override
    protected void before() throws Throwable {
        super.before();
        instance = Hazelcast.newHazelcastInstance();
        service = instance.getExecutorService(SERVICE_NAME);
    }

    @Override
    protected void after() {
        super.after();
        service.shutdown();
        instance.shutdown();
    }

    public HazelcastInstance getInstance() {
        return instance;
    }

    public IExecutorService getService() {
        return service;
    }
}

IdMultiMapAccessIT

Here is an example of using the IdGenerator to create new “playgrounds” or keys for the threads to place data.

package com.darylmathison.multimap;

import com.darylmathison.multimap.test.rule.HazelcastInstanceResource;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IExecutorService;
import com.hazelcast.core.IdGenerator;
import org.junit.ClassRule;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Integration test for IdMultiMapAccessThread
 */
public class IdMultiMapAccessThreadIT {

    public static final String MAP_NAME = "idAccessMap";
    public static final String GEN_NAME = "singleAccess";
    public static final int NUM_THREADS = 10;

    @ClassRule
    public static HazelcastInstanceResource hazelcastInstanceResource = new HazelcastInstanceResource();

    @Test
    public void testIdThreads() {
        List threads = generateThreads(hazelcastInstanceResource.getInstance());
        List<Future<?>> futures = new ArrayList<>(NUM_THREADS);
        IExecutorService spinner = hazelcastInstanceResource.getService();
        for(IdMultiMapAccessThread thread: threads) {
            futures.add(spinner.submit(thread));
        }

        for(Future<?> future: futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    private List generateThreads(HazelcastInstance instance) {
        IdGenerator gen = instance.getIdGenerator(GEN_NAME);
        List threads = new ArrayList<>(NUM_THREADS);
        for(int i = 0; i < NUM_THREADS; i++) {
            IdMultiMapAccessThread thread = new IdMultiMapAccessThread();
            thread.setMapName(MAP_NAME);
            thread.setId(gen.newId());
            threads.add(thread);
        }

        return threads;
    }
}

GroupMultiMapAccessThreadIT

This is an example of using an IdGenerator to create a shared playground or slot.

package com.darylmathison.multimap;

import com.darylmathison.multimap.test.rule.HazelcastInstanceResource;
import com.hazelcast.core.IExecutorService;
import com.hazelcast.core.IdGenerator;
import org.junit.ClassRule;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * GroupMultiMapAccessThread Integration Test
 */
public class GroupMultiMapAccessThreadIT {
    public static final int NUM_THREADS = 10;
    public static final String GEN_NAME = "groupIdGenerator";
    public static final String MAP_NAME = "groupMap";

    @ClassRule
    public static HazelcastInstanceResource hazelcastInstanceResource = new HazelcastInstanceResource();

    @Test
    public void testGroupMultiMapAccessThread() {
        List threads = createThreads();
        IExecutorService service = hazelcastInstanceResource.getService();
        List<Future<?>> futures = new ArrayList<>(NUM_THREADS);
        for(GroupMultiMapAccessThread thread: threads) {
            futures.add(service.submit(thread));
        }

        for(Future<?> future: futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    private List createThreads() {
        List ret = new ArrayList<>(NUM_THREADS);
        IdGenerator gen = hazelcastInstanceResource.getInstance().getIdGenerator(GEN_NAME);
        Long groupId = gen.newId();
        for(int i = 0; i < NUM_THREADS; i++) {
            GroupMultiMapAccessThread thread = new GroupMultiMapAccessThread();
            thread.setMapName(MAP_NAME);
            thread.setGroupId(groupId);
            ret.add(thread);
        }

        return ret;
    }
}

Conclusion

In this post, Hazelcast’s MultiMap was profiled. It was shown that MultiMaps can store multiple values for a given key. It was also shown how a thread can share the data in a MultiMap or can store data for itself using the IdGenerator as a possible key generator.  The code can be found in GitHub here.

References

http://www.hazelcast.com
http://www.hazelcast.org
https://github.com/hazelcast/hazelcast