1

How, in an EJB environment, can I force interaction with any given resource in a collection of resources to be single threaded, without limiting access to the collection itself? I want to allow one thread to interact with resource A while another is interacting with resource B; but prohibit two threads from interacting with the same resource at the same time.

The back story: I've got multiple devices on a network, and multiple threads within my application that might want to talk to any given device. The devices themselves are dumb and have no concept of a session, which means that, without an access control mechanism, it's likely that messages from different threads to the same device will interleave.

The pool of devices is potentially hundreds, but not thousands. It is also somewhat dynamic - devices appear and drop.

I could roll my own class that manages concurrency for a single device, instantiate one for each device, and then have a singleton bean that manages the collection and dispatches requests to the individual instances.

But most or all of this must be already taken care of, somewhere in Java's concurrency mechanisms?

Is there a well-established pattern here that I should be using?

Chris Owens
  • 1,107
  • 1
  • 10
  • 15
  • With singleton EJB the container can synchronize each concurrent request allowing that some functionalities execute in a single-thread model. I know that you have already thought in to use a Singleton EJB, but it's not clear for me why this is not suitable for your problem. – Gabriel Aramburu Oct 01 '14 at 21:40
  • How would you use a singleton EJB to achieve what I am trying to achieve here, namely to allow many threads to access many devices in parallel, but for any one device, only one thread at a time can access it. Short of (manually) creating a separate singleton EJB for each device, what else could I do? – Chris Owens Oct 01 '14 at 23:00

1 Answers1

1

Are you sure that you want to use EJB for that ? Mixing standard java concurrent mechanisms and JavaEE is rather discouraged...

See: why-spawning-threads-in-java-ee-container-is-discouraged

Community
  • 1
  • 1
cichystefan
  • 328
  • 2
  • 10
  • I don't spawn any threads directly - I leave everything to the container, which implements JSR-236. The container might have multiple threads running, each of which might try to talk to a given device, which is where the problem arises. – Chris Owens Oct 01 '14 at 18:47
  • Ok, than if I were you I would make those threads access single Singleron EJB. I would annotate it with @ConcurrencyManagement(BEAN) and implement neccesary synchronizations mechanisms by myself. – cichystefan Oct 03 '14 at 18:06