1

I would like to create a worker thread that should be shared within other sessions. Basically I want to restrict other users from doing the same process. So They will retrieve the thread via a static Instance of object thread that I created. If the thread is still alive, then they will be prompted with error.

Is there a other way to do this because I am thinking if placing a Thread object within a static is safe? I am also thinking of application context but I am not sure which is better way to do this in java?

3 Answers 3

2

Placing any object in a static or in any kind of shared location is not intrinsically unsafe but you need to take care with the design.

declare

 static Thing t; 

initialise

 if ( t == null ) { t = new Thing(); } 

use

t.dosomething(); 

Now what happens if two threads hit the initialise block at the same time? You can get two Things created. Probably don't want that, so use synchronisation.

synchronized void intialise() { if ( t == null ) { t = new Thing(); } } 

what happens if two threads attempt to use the t at the same time. This depends on the promises made by Thing. If it's thread-safe no problem, otherwise your code needs to provide synchronisation

 synchronized void doSomthing() { t.doSomething(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thing could be anything, there's nothing special about a Thread object.
1

I would use a lock for the static field you set so you avoid the possibility that two tasks start the process. You can store the Thread so you know when it is finished or an AtomicBoolean to flag when it is running. (Which you can also lock on)

2 Comments

So is it safe to store the Thread as static? I mean if I store it session, it is not accessible to other sessions.
Its safe provided its thread safe. However it is not normal practice and its worth commenting why it is done.
1

You can have a atomic boolean to flag the status of your worker thread and return the thread only if it false.

you would need to set it to true when the worker thread is starts.

2 Comments

I know but the atomic boolean might not give me the real time status of the thread. If it is just status it is ok but I would like to retrieve several info that is within the thread like a list of status messages. Or should i also place the status message as an static list?
If any other info i required, then keep all such info in some wrapper and guard the wrapper object using a Lock whenever you access it (for both read / write). This is important as you should not allow a direct reference to a shared object. All access should be synchronized.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.