Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

deadlock static int / performence ???

 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have methoed that is call from many difrent portlets:



The pcUniqueName is a class member defined as:

static int pcUniqueName;

I need a unique number in the JVM, this is called from many difrent portlets at the same time....

Can this give deadlock in any way ???

If this cant give any deadlock, and if example 50 portlets calls the mothoed at almost the same time, the last portlet must wait for the other 49 portlets !

Cann i optimize this code in any way ???

Frank
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The risk you run right now is the "race condition". Thread1 might increment pcUniqueName and then Thread2 might increment it again before T1 returns. So T1 and T2 might return the same value. The fix is to synchronize the method or the smallest possible block of code around the incrementer. That will force the 50 portlets to come through the method single-file. Since the method is very fast synchronizing the method won't hurt much.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What Stan said goes, but I wanted to give you a little background.

First, "Deadlock" always refers to an interaction that happens when two threads try to lock two different objects in the opposite order. In a deadlock situation, thread A has locked object 1 and is waiting to lock object 2; which thread B has locked object 2 and is waiting to lock object 1. The two threads will wait forever, and this is called a "deadlock." This has nothing to do with your current situation, as there's only one object being used, and in fact no locking at all.

Second, note that threads don't block eachother from calling unsynchronized methods. As Stan describes, many threads can be inside the same unsynchronized method on the same object at the same time. If they're all modifying a common resource, as here, then this is a recipe for disaster!

I'm going to move this to our "Threads and Synchronization" forum.
 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THANKS
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic