views:

62

answers:

1

In a program, I am trying to make unique id numbers. I used this way:

AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet();
int pid = count.get();
System.out.println("pid: " + pid);

But my professor said this:

Another problem is the pid generation. All you are doing is getting the next integer starting from 0. What happens when you reach the end of the process table? You had to come up with your own pid generation algorithm that works according to the project specification, i.e. it cycles through the numbers 0 through 99, and then when it cycles back to the low number it starts with the lowest available pid. There are many ways to implement such an algorithm, but the simplest thing to do is to add 1 mod 100, then keep looking until you find an available pid. Of course that means you have to keep track of which pids are available.

How do I do that?

+3  A: 

To me your professor's explanation is quite clear - is there any specific part in it that you don't understand?

If you understand the individual parts, divide the task into smaller subtasks and implement those one by one. Like

  1. cycle through the numbers from 0 to 99 (after 99, the next number should be 0 again)
  2. add a facility to store the numbers generated so far (e.g. in a collection)
  3. add a facility to check that the current number is not used yet
  4. (add a facility to free a used process number when the associated process terminates - it is not clear from the description whether or not you need this.)
Péter Török
2. is a hashset a good idea??
Luron
@Luron, perfect - that would be my first choice as well :-)
Péter Török
1. linkedlist would work right? 4. yes i do need that. but how do i do that?
Luron
@Luron, 1. depends on how you use it - it may be useful in some algorithms, but useless in others. For the simplest solution (as explained by your professor) you don't need it. 4. implement a method `freePid(int pid)` which removes the given pid from the collection of used pids.
Péter Török
i still don't understand how to do this? i have to keep the pid in one program and declare the value in another class
Luron
@Luron, when you have generated a new unused PID (presumably in a method called e.g. `getNextPid()`), you add it to the collection of used PIDs. When `freePid` is called, you remove the given PID from the collection.
Péter Török