Run java function in thread - multithreading

Is there way to run function/method in its own thread?
I have two use cases for this right now. One is that I have a Consumer<T> that is passed in. I want to run this on its own thread as it will take a long time to finish.
The other use case that I have is that I have a number of functions in the same class that I want to run in their own threads individually (one thread per function). These functions need access to private data in their class's state.
Is there a way to do this in java?
Update: For what its worth, I know about the "normal" way of doing this, either by extending Thread, or implementing runnable. However, in both of these cases those approaches don't work.
Update 2:
Implementing Runnable won't work as the class has a number of different methods that all have to be independently "run" on their own threads. Given that there are quite a few methods in this class that would need to run threads, this won't work. Since these threads require access to some shared private data, I can't even split each method into its own class (even though that would not map to what I would consider a logical class anyway).
For the case where I have a Consumer<T> I can't extend/implement Thread/Runnable as I don't control the interface. The method takes a Consumer<T> as a parameter, and I need to call it in it's own thread. I suppose here I could create a wrapper class, but then I would have to create (I think) one wrapper class each for Consumer, Function, etc. And all of this seems rather needless (at least coming from other languages).
Update 3: Assume that synchronization is not an issue (data is either immutable, or contention is very low)
I am looking for a better way. Is this clearer?

As a partial solution for the functions / methods (if they don't need arguments) you can use Threads or an ExecutorService and method references.
If you need arguments you will have to write lambda expressions - see the method t3 and it's start for an example.
public class Test {
public void t1() {
System.out.println("t1");
}
public void t2() {
System.out.println("t2");
}
public void t3(int n) {
System.out.println("t3:"+n);
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
Thread t = new Thread(test::t1);
t.start();
ExecutorService es = Executors.newFixedThreadPool(5);
es.submit(test::t2);
es.submit(() -> test.t3(99));
es.shutdown();
es.awaitTermination(1, TimeUnit.SECONDS);
}
}

Related

Appropriate use of synchronizing or locking a segment of code

Given a singleton class Employee with 2 methods
int getSalary()
void updateSalary(int increment)
Do I need to synchronize or lock both these functions or use atomic salary variable?
If yes then the question is that in this way we would have to synchronize all the functions that we define in multithreaded environment. So, why not just make synchronized a standard as today no real world application would be single threaded?
With Singleton, we always have to very careful because, singleton object being a single instance naturally, can be shared between threads. Making functions synchronized is one way, and it is not efficient way. We need to think about other aspect of concurrency, like immutability Atomic classes.
class Employee {
//singleton instantiation
private final AtomicInteger sal = new AtomicInteger(0);
int getSalary(){
return sla.get();
}
void updateSalary(int increment){
sla.add(increment);
}
}
This will solve, we do not need to synchronize every method of the singleton class.
We do not have to mark every function of every class to be synchronized, but always have to be careful if a function is modifying a state or reading a state and could be concurrently invoked, in such cases start thinking about synchronization. But, with singleton classes we always have to be careful.

MFC Thread-safe singleton

I want to create a thread-safe singleton using only MFC. I prefer to avoid boost::thread, and I can't use std::thread on VS2010.
Also, VS 2010 has C++11 limitations (if not, it would be much easier since I think it supports thread-safe static variable initialization).
So far, I have tried this solution but I'm not sure how thread-safe it is.
From my understanding, a problem would be that the static CCriticalSection was initialized after the singleton instance is created and some trouble would appear if two threads get an instance and generate two singleton objects.
In my case there will be only two threads running simultaneously, one main thread and one worker thread. The main thread will get the first instance, and the worker threads will get instances from time to time afterwards.
In this scenario, is this class thread-safe enough? Am I missing something?
In case that there's no way to do a thread-safe enough singleton class with MFC only I'll consider boost. Any advice or suggestion is highly appreciated.
// Singleton.h
class CSingleton
{
static CCriticalSection m_cs;
public:
static CSingleton& GetInstance()
{
m_cs.Lock();
static CSingleton instance;
m_cs.Unlock();
return instance;
}
virtual ~CSingleton(){};
private:
CSingleton(){}; // Constructor
CSingleton( CSingleton const& ); // Don't Implement
void operator=( CSingleton const& );
}
// Singleton.cpp
// Initialize Critical Section
CCriticalSection CSingleton::m_cs;

How do I create a scheduler which never executes more than one Task at a time using async-await?

I want to implement a class or pattern that ensures that I never execute more than one Task at a time for a certain set of operations (HTTP calls). The invocations of the Tasks can come from different threads at random times. I want to make use of the async-await pattern so that the caller can handle exceptions by wrapping the call in a try-catch.
Here's an illustration of the intended flow of execution:
Pseudo code from caller:
try {
Task someTask = GetTask();
await SomeScheduler.ThrottledRun(someTask);
}
catch(Exception ex) {
// Handle exception
}
The Taskclass here might instead be an Action class depending on the solution.
Note that I when I use the word "Schedule" in this question I'm not necessarily using it with relation to the .NET Task Scheduler. I don't know the async-await library well enough to know at what angle and with what tools to approach this problem. The TaskScheduler might be relevant here, and it may not. I've read the TAP pattern document and found patterns that almost solve this problem, but not quite (the chapter on interleaving).
There is a new ConcurrentExclusiveSchedulerPair type in .NET 4.5 (I don't remember if it was included in the Async CTP), and you can use its ExclusiveScheduler to restrict execution to one Task at a time.
Consider structuring your problem as a Dataflow. It's easy to just pass a TaskScheduler into the block options for the parts of the dataflow you want restricted.
If you don't want to (or can't) use Dataflow, you can do something similar yourself. Remember that in TAP, you always return started tasks, so you don't have the "creation" separated from the "scheduling" like you do in TPL.
You can use ConcurrentExclusiveSchedulerPair to schedule Actions (or async lambdas without return values) like this:
public static ConcurrentExclusiveSchedulerPair schedulerPair =
new ConcurrentExclusiveSchedulerPair();
public static TaskFactory exclusiveTaskFactory =
new TaskFactory(schedulerPair.ExclusiveScheduler);
...
public static Task RunExclusively(Action action)
{
return exclusiveTaskFactory.StartNew(action);
}
public static Task RunExclusively(Func<Task> action)
{
return exclusiveTaskFactory.StartNew(action).Unwrap();
}
There are a few things to note about this:
A single instance of ConcurrentExclusiveSchedulerPair only coordinates Tasks that are queued to its schedulers. A second instance of ConcurrentExclusiveSchedulerPair would be independent from the first, so you have to ensure the same instance is used in all parts of your system you want coordinated.
An async method will - by default - resume on the same TaskScheduler that started it. So this means if one async method calls another async method, the "child" method will "inherit" the parent's TaskScheduler. Any async method may opt out of continuing on its TaskScheduler by using ConfigureAwait(false) (in that case, it continues directly on the thread pool).

QNetworkAccessManager from ThreadPool

A very fundamental question. The documentation mentions that all methods in QNetworkAccessManager are reentrant. If so, is performing a get() method in a QRunnable without locks legal? My code would look something like this:
class MyClass: public QRunnable
{
void run()
{
...
QNetworkAccessManager nam;
QNetworkReply* reply = name.get(request) // No Read-write lock.
...
}
};
From the Qt documentation:
[...] a class is said to be reentrant if its member functions can [simultaneously] be
called safely from multiple threads, as long as each thread uses a different instance of
the class.
Since you're using a different instance each time (the one you create on the stack in run()), you're on the safe side.
As a side note to this ,if you just want the GET request to be asynchronous, QNetworkAccessManager is already asynchronous (says so in the docs).

Invoking time-consuming JNI task as a thread

I'm having a tough problem with invoking a native function using JNI from a thread.
The native function is legacy code that performs a computation-intensive task. Since I'd like not to freeze the rest of the program, the computation should be performed in a background thread. EventBus is used to send the calculation result back to the main program.
Basically it should be quite simple, something like this:
public class CalculationEngine {
private CalculationEngine(){}
public static void calculateInBackground(final Parameters parameters) {
new Thread(new Runnable() {
public void run() {
// Someone might change the parameters while our thread is running, so:
final Parameters clonedParameters = parameters.clone();
Results results = new Results();
natCalc(clonedParameters, results);
EventBus.publish("Results", results);
}
}).start();
}
public static void calculateNormally(final Parameters parameters) {
Results results = new Results();
natCalc(parameters, results);
EventBus.publish("Results", results);
}
private static native synchronized void
natCalc(Parameters parameters, Results results);
}
Now, the calculateNormally method, which blocks the main program, works fine, but the calculateInBackground method, which just constructs a background thread to do the same thing, causes various crashes in the native code when it's invoked consecutively. By consecutively I mean that it's called again only after the previous thread has finished and returned the result. Note that the native code is marked synchronized to ensure that only one instance of it can be running at a time.
My question is, how on earth can the native code behave differently depending on whether it's invoked from the main thread, or from some other thread? It's like the native code were keeping "state", and not really quitting, when it's called from within a thread other than the main thread. Is there a way to "clean" or "flush" a thread after it's finished? There must be something in JNI & Threads that I simply don't know.
Thanks for any hints!
I figured out a working solution, after googling and finding the phrase "I've found JNI to be very buggy when called from seperate threads... So make sure only one thread ever calls your native code!". It seems to be true; the solution is to keep a persistent, "reusable" thread around - I used Executors.newSingleThreadExecutor() - and to call the native code only from that thread. It works.
So the difference from JNI point of view was not between main thread vs. some other thread, but in using different threads in consecutive calls. Note that in the problematic code a new thread was constructed each time. It should work that way, but it doesn't. (And no, I'm not caching JNIEnv pointer.)
Whether it's a JNI bug, bug in the native code, something in the interaction between them and OS or whatever, would be interesting to know. But sometimes you just have no chance to debug 10000+ lines of existing code in detail, however, you're happy to get it to work. Here's working version of the example code, let's call this a workaround:
public class CalculationEngine {
private CalculationEngine(){}
private static Parameters parameters;
private static ExecutorService executor = Executors.newSingleThreadExecutor();
private static Runnable analysis = new Runnable() {
public synchronized void run() {
Results results = new Results();
natCalc(parameters, results);
EventBus.publish("Results", results);
}
};
public static synchronized void
calculateInBackground(final Parameters parameters) {
CalculationEngine.parameters = parameters.clone();
executor.submit(analysis);
}
private static native synchronized void
natCalc(Parameters parameters, Results results);
}
My advice on using JNI is DON'T if you can possibly avoid it. The chances are that it will cause stability issues for you. Here are some possible alternatives:
Recode the native library in Java.
Write a wrapper command for the native library in C / C++ / whatever and run it using java.lang.Process and friends
Turn the native library into a daemon and access it using Sockets.
While you've got an answer, I don't think too much has been provided as to possible root cause. Here's a few possibilities, but there are others. Note, these apply to Windows.
There's an apartment threaded COM object involved. Apartment threaded COM objects, which are the only type VB can create, can only be used on the thread that creates them.
Security features, like impersonation, are often thread isolated. If the initialization code modified the context of the thread, future calls that expect the context to be in place will fail.
Thread specific memory storage is a technique within some applications to support multi-threadedness (Java also has such a feature).
Here there is a good documentation about it: Section 8.1 JNI and Threads.
http://java.sun.com/docs/books/jni/download/jni.pdf

Resources