dagblog.
← Archive

Programming puzzle


Inspired by the series of programming puzzles from René Stein, I decided
 I'd share any tricky surprises or bugs I came across. Unfortunately, I didn't have to

wait long. I have the following code in the application server's business logic.

public class CisRozpKapService implements ICisRozpKapService {    

private volatile int maxSkupId = 0;
.
.
.

public int saveSkupina(int kapitola, String nazev) {
CisRozpKap kap = rozpKapDao.load(kapitola);
CisRozpKapSkup skup = new CisRozpKapSkup();
skup.setCisRozpKap(kap);
skup.setNazev(nazev);
synchronized(this){
maxSkupId++;
}
skup.setSkupina(maxSkupId);
rozpKapSkupDao.save(skup);
return skup.getSkupina().intValue();
}

.
.
.
}

To clarify, maxSkupId has to be unique for each object 
being saved… Can you find and fix the bug?

Medium version

Related articles

Related CZ Podcast episodes