How to Use Sequence Generator in Java


Here we will learn how to create a sequence generator in Java.

Source Code

1)SequenceGeneratorExample1

package com.beginner.examples;

public class SequenceGeneratorExample1 {

	private long idNum = 1;
	
	public Long next() {
		// TODO Auto-generated method
		return idNum++;
	}
}

2)SequenceGeneratorExample2

package com.beginner.examples;

import com.beginner.examples.SequenceGeneratorExample1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class SequenceGeneratorExample2 implements Callable<List> {

    private SequenceGeneratorExample1 idNum;

    public SequenceGeneratorExample2(SequenceGeneratorExample1 idNum) {
        this.idNum = idNum;
    }

    @Override
    public List call() throws Exception {

        List sequence = new ArrayList();

        for (int i = 1; i <= 7; i++) {
        	//sleep 200
            Thread.sleep(200); 
            sequence.add(idNum.next());
        }

        return sequence;

    };
}

3)SequenceGeneratorExample3

package com.beginner.examples;

import com.beginner.examples.SequenceGeneratorExample1;
import com.beginner.examples.SequenceGeneratorExample2;

import java.util.List;
import java.util.concurrent.*;

public class SequenceGeneratorExample3 {

    public static void main(String[] args) {

    	SequenceGeneratorExample1 idNum = new SequenceGeneratorExample1();

        ExecutorService pool = Executors.newCachedThreadPool();

        try {

			// simulate 3 threads concurrent access the sequence generator
            Callable<List> run1 = new SequenceGeneratorExample2(idNum);
            Callable<List> run2 = new SequenceGeneratorExample2(idNum);
            Callable<List> run3 = new SequenceGeneratorExample2(idNum);
            Callable<List> run4 = new SequenceGeneratorExample2(idNum);

            Future r1 = pool.submit(run1);
            Future r2 = pool.submit(run2);
            Future r3 = pool.submit(run3);
            Future r4 = pool.submit(run4);

            System.out.println(r1.get());
            System.out.println(r2.get());
            System.out.println(r3.get());
            System.out.println(r4.get());

        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        	pool.shutdown();
        }

    }

}

Output:

[2, 7, 10, 15, 18, 21, 26]
[3, 6, 9, 14, 19, 20, 24]
[1, 5, 11, 13, 17, 23, 27]
[1, 4, 8, 12, 16, 22, 25]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments