Java Dynamic number thread Creation and Mangement - java

I want to create dynamic number of thread which is depends on the database Number of database rows..
List list = session.createQuery("From Devices").list();
Number of thread is depends on the list.size().
I am Creating dynamic number of thread using For loop
new Thread(){public void run(){/* Task of each thread */}.start();
Is it right way to create dynamic number of thread ?? If i use shared variable do I need to define synchronized.. Any another idea how to manage thread where thread count become dynamic and depends on User.
Another question how can i define some private variable which is separated to each thread and not sheared to each other ..????
thanks

If you just need a team of threads to execute something on every row I would instead use a thread pool:
ExecutorService exec = Executors.newFixedThreadPool(list.size());
It's much easier to submit work and manage the pool than using an array of threads.
After this, synchronization depends on the actual computation. If you are concurrently modifying some shared state (list, counter) you will need to synchronize access across threads.
Finally, to define a thread task with private state:
class ThreadTask implements Runnable {
private int state; // example of private state
public ThreadTask(int state) {
this.state = state;
}
public void run() {
// task code
}
}

Is it right way to create dynamic number of thread ??
Yes, but not very elegant. Consider creating a separate class:
public class DeviceHandler implements Runnable {
//...
}
and then:
List<Device> list = session.createQuery("From Devices").list();
for(Device device: list) {
Thread thread = new Thread(new DeviceHandler(device));
thread.start();
}
Note that I assume each thread is responsible for a device so I am eagerly passing Device instance to each thread. You'll need it, trust me.
If i use shared variable do I need to define synchronized..
If multiple threads are accessing the same variable, you have to use some sort of synchronization: synchronized, Lock, volatile, Atomic*... This is way too broad for this question.
Any another idea how to manage thread where thread count become dynamic and depends on User.
Not sure what you mean. The thread count is dynamic in your current solution.
Another question how can i define some private variable which is separated to each thread and not sheared to each other ..????
Well, in Java you actually can't have variables local to thread (escept obscure ThreadLocal) because everything lives on global heap. However if you encapsulate some variable and let only a single thread to access it, you'll be safe:
public class DeviceHandler implements Runnable {
private int noGettersAndSettersForMe;
}

Related

Prevent several threads from entering the same method of different objects

Please skip to the TLTR if you do not want to read the whole story but the question:)
I need to fix a bug in our system and I have found the bug but could not find an optimal solution for this problem.
As an illustration, what it is aimed to be done is; when there are three files to be closed and for each file, a different thread (3 threads in this example) is created and should get the id of the file and by using file's id, it should close the file.
However, the person, who programs this, did not think something genuinely. At the moment, three threads are created for three different files and they access to the method, which distributes the ids, at the same time and the method gives the id of the first file (normally, first id to first thread, second id to second thread and third id to the third thread should be given) to three threads and these three threads try to close the same file (which causes the bug).
I cannot change this structure and it should be remain as it is.
TLTR
What I try to achieve is; how can I prevent several threads from entering the same method at the same time?
I tried synchronized (and lock) strategies for this but they did not help me in this situation, because each thread has its own lock (there are several objects created).
Create a singleton.
public static final Object globalLock = new Object();
Then in your methods where you need to protect.
synchronized(globalLock){
//get your file ids.
}
Couple of ways for doing this, here are some:
Make method synchronized
public class MyClass{
public void synchronized mySynchronizedMethod(); // only single thread will be allowed to invoke this method on the SAME INSTANCE OF MyClass
public void notSynchronizedMethod();
}
Use synchronized block:
MyClass obj=new MyClass();
synchronized(obj){
// only single thread is allowed to enter that block WITH obj INSTANCE.
obj.notSynchronizedMethod():
}
Synchronize on class
MyClass obj=new MyClass();
synchronized(MyClass.class){
//single thread is allowed for this block in a scope of WHOLE CLASS LOADER so in most cases you can say it is "globally" synchronized
}
Use Semaphore
Semaphore sem=new Sempahore(1);
sem.aquire(); // Thread will aquire permit, another thread will wait
//this will be synchronized block
sem.release(); allows another thread to aquire permit

Creating fields with a single instance per thread with Java

I am trying to parallelize a bit of code which makes use of static fields within a "Constants" class. The code at the moment essentially looks like this
public class myClass{
public class Constants{
public static int constant;
}
public static void main(String[] args){
for(int i = 0 ; i<10 ; i++){
Constants.constant = i;
System.out.println(Constants.constant/2);
}
}
}
Obviously the code within the loop is much more heavily dependent on the Constant class, which itself is much more complex. What I'd like to do is create a thread for each iteration of the loop and do said computations separately, all the while controlling the number of threads (right now I'm using a simple semaphore).
Now obviously in the above code, the Constants class is shared between threads and thus cannot be updated by each thread without being updated for all of them.
So my question is : is there anyway to make my Constants class be able to have an instance for each thread, all the while being able to access its fields in a static manner ?
What you're describing is a thead-local: http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html . It's a good thing to use. However, as Affe points out, you can't use that with your code as is, because there's just one instance of the class and its static members (per classloader). If your Constants class is something that you can build several several copies of in parallel and then merge them together later, you should make Constants.constant an instance variable by removing "static". Then create a thread-local in myClass like so:
private ThreadLocal<Constants> constants = new ThreadLocal<Constants> {
#Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
}
Once your threads are done updating their local object, they can stick them into a shared ArrayBlockingQueue. Your main thread can dequeue them all and merge them as you desire.
Another thing to note is that you may want to use a thread pool executor instead of one thread per iteration of the loop, if you will have a variable number of iterations, possibly many, but you don't want that many threads. (Thread creation is costly and many concurrent threads eat memory and OS scheduling resources.)

Sending work to a pool of workers that need initialization

I have a problem that seems close to what Executors and Thread pools do, however I can't seem to make it exactly fit. Basically I have workers which take a bit of time to initialize and that I'd like to pool, and once they are ready I use them to do work. I need to do this in a Thread :
worker = buildExpensiveWorker();
worker.doWork(work1);
worker.doWork(work2);
worker.doWork(work3);
...
While an Executor only allows me to do this :
doWork(work1);
doWork(work2);
doWork(work3);
...
Will I need to write my own Thread pool ? It feels like a shame to rewrite what is already well done. Or will I need to use ThreadLocal to hold my workers, and manage them from inside the Runnable's run() method ?
If you're talking about actually initializing the Thread objects prior to them being available for use, take a look at ThreadPoolExecutor.setThreadFactory:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#setThreadFactory(java.util.concurrent.ThreadFactory)
You can provide your own implementation create a thread in any manner you want, including creating custom Thread subclasses and/or custom initialization.
I would say however, that if your initialization is expensive, you should probably try to configure the executor to keep the actual threads alive as long as possible (ie, set the keep alive time rather high, and try to spin up all the threads you need right away, and take the hit up front).
EDIT: Using a thread local (as mentioned in the comments):
public class ThreadData {
public static final ThreadLocal<String> data = new ThreadLocal<String>();
}
public class InitializingThread extends Thread {
public InitializingThread(Runnable r) {
super(r);
}
public void run() {
ThreadData.data.set("foo");
super.run();
}
}
public class InitializingThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new InitializingThread(r);
}
}
ThreadPoolExecutor executor = ...;
executor.setThreadFactory(new InitializingThreadFactory());
executor.execute(...);
And then in your Runnable:
public void run() {
String s = ThreadData.data.get();
}
Also, this approach (as opposed to using using Thread.currentThread() and casting) has the advantage of being able to actually be used with any Thread implementation (including the default), or without a thread (directly calling the .run() method after setting the value in the ThreadLocal). You could also easily change "ThreadLocal" to "InheritableThreadLocal", and set it once before submitting anything to the thread pool. All child threads would inherit the value from their parent thread (the one which created the pool).
It's important to note that the "run" method of a given thread will only ever executed once, even when in a thread pool, so this guarantees that your initialization routine happens on a per thread basis.

Can a thread Object be set to a static variable

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?
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();
}
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)
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.

Java synchronized methods question

I have class with 2 synchronized methods:
class Service {
public synchronized void calc1();
public synchronized void calc2();
}
Both takes considerable time to execute. The question is would execution of these methods blocks each other. I.e. can both methods be executed in parallel in different threads?
No they can't be executed in parallel on the same service - both methods share the same monitor (i.e. this), and so if thread A is executing calc1, thread B won't be able to obtain the monitor and so won't be able to run calc2. (Note that thread B could call either method on a different instance of Service though, as it will be trying to acquire a different, unheld monitor, since the this in question would be different.)
The simplest solution (assuming you want them to run independently) would be to do something like the following using explicit monitors:
class Service {
private final Object calc1Lock = new Object();
private final Object calc2Lock = new Object();
public void calc1() {
synchronized(calc1Lock) {
// ... method body
}
}
public void calc2() {
synchronized(calc2Lock) {
// ... method body
}
}
}
The "locks" in question don't need to have any special abilities other than being Objects, and thus having a specific monitor. If you have more complex requirements that might involve trying to lock and falling back immediately, or querying who holds a lock, you can use the actual Lock objects, but for the basic case these simple Object locks are fine.
Yes, you can execute them in two different threads without messing up your class internals but no they won't run in parallel - only one of them will be executed at each time.
No, they cannot be. In this case you might use a synchronized block instead of synchronizing the whole method. Don't forget to synchronize on different objects.

Categories

Resources