java线程中的唯一ID

发布于 2024-12-27 15:26:56 字数 369 浏览 6 评论 0原文

我的应用程序使用一个日志组件,该组件需要跟踪每个调用的唯一标识符。

我的出发点是一个 MDB,它显然启动了对几个类的一系列方法调用。 每个类都会创建一个新的记录器对象(类似于 log4j),并使用它来将事件记录到数据库中。对于创建的每个记录器对象,都会为其分配一个唯一的标识符。该标识符应该跟随线程,直到后续调用全部返回并且我的 MDB 中的 onMessage 方法终止。

问题是在处理一条 JmsMessage 期间,MDB 收到另一条消息,并且我的 ID 混淆了。

我已经用头撞桌子有一段时间了,我想答案就在我面前,但是你有什么想法吗?我怎样才能确保一个“进程”可以使用自己的 ID 进行日志记录,即使另一个“进程”在第一个进程完成之前启动?

先感谢您。

My application uses a logging component which needs to keep track of a unique identifier for each call.

My starting point is an MDB which obviously initiates a series of methodcalls to several classes.
Each class creates a new logger-object, similar to log4j, and uses this to log events to the database. And for each logger-object that gets created, a unique identifier is assigned to it. This identifier should follow the thread until the subsequent calls all return and the onMessage-method in my MDB terminates.

The problem is that during the processing of one JmsMessage, another message is received by the MDB and my IDs get mixed up.

I have been banging my head against the desk for some time now and I guess the answer is right in front of me, but have you got any ideas? How can I make sure that one "process" can log using its own ID even if another is started before the first one finishes?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小巷里的女流氓 2025-01-03 15:26:56

是否有原因无法使用 Message.getJMSMessageID()

如果有,AtomicLong.incrementAndGet() 应该就足够了。保留一个静态实例,并在 MDB 的 onMessage() 方法中获取一个 ID,并在处理消息时保留它(可能在 ThreadLocal 中)。

Is there a reason you can't use Message.getJMSMessageID() ?

If there is, AtomicLong.incrementAndGet() should be all it takes. Keep one static instance, and in the MDB's onMessage() method get an ID and keep it around while the message is processed (perhaps in a ThreadLocal).

帝王念 2025-01-03 15:26:56

通常您希望使用“友好”名称

String name = Thread.currentThread().getName();

,但是,这可能不唯一或没有意义,在这种情况下您可以使用唯一的 ID。

int id = Thread.currentThread().getId();

Usually you want to use the "friendly" name

String name = Thread.currentThread().getName();

However, this might no be unique or meaningful in which case you can use a unique id.

int id = Thread.currentThread().getId();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文