Rules for generating unique server IDS

Source: Internet
Author: User

When hashcode is used, the same ID will appear, although the probability is very small. Although it is not the reason for hashcode, it is another logic problem.

However, I tried to write an ID generator myself. Some IDs are int, for example, task id, and some IDs are long, for example, player ID.

First paste the code to see:

Private Static atomicinteger id = new atomicinteger (0); public static long GETID () {return (serverkit. getserverid () & 0 xFFFF) <48 | (system. currenttimemillis ()/1000l & 0 xffffffff) <16 | ID. addandget (1) & 0 xFFFF;} Private Static atomicinteger intid = new atomicinteger (0); public static int getintid () {return (INT) (system. currenttimemillis ()-interval limit L)/1000) <16l | (intid. addandget (1 ));}
View code

When generating the player ID, the server ID is also involved to facilitate later combination.

Because the server is multi-threaded, The atomicinteger type is used, and synchronization tools such as sync are no longer needed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.