Is there a way to use custom executor in Hazelcast? - java

It is possible to configure custom executor using ExecutorConfig, e.g.:
Config config = new Config();
config.getExecutorConfig("my-custom-executor").setPoolSize(40).setName("my-executor");
This will finally create some java.util.concurrent.ThreadPoolExecutor child.
But how can I specify customly created java.util.concurrent.ExecutorService implementation as some named executor in Hazelcast?

Creating a custom j.u.c.ExecutorService managed by Hazelcast is not possible at the moment (current latest GA version is 3.12.5 and 4.0 is about to be released). All executors share the same cached thread-pool using separate task queues per custom executor (see CachedExecutorServiceDelegate). And this shared thread pool is an instance of j.u.c.ThreadPoolExecutor.
I think it should be fairly easy to add this as a new feature. You can create an issue at Issue Tracker or better send a pull request with an implementation.

Related

Naming threads in Spring

I thought it was always recommended to name your threads to make it easier to debug later on.
In my SpringBoot project I now used the #Async notation and later on a TaskExecutor, but could not find a way to name my threads.
Is there a way to do that, or not really done in the Spring abstractions?
You can use thread prefix conf property in task executor configuration, or you can use ThreadFactory if prefix is not enough
#Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("my_thread_prefix");
executor.setThreadFactory( new ThreadFactoryBuilder().setNameFormat("my-thread-%d").build())
executor.initialize();
return executor;
}
TaskExecutor in Spring is a functional interface that extends directly from Java's Executor. According to the documentation:
An object that executes submitted Runnable tasks. This interface
provides a way of decoupling task submission from the mechanics of how
each task will be run, including details of thread use, scheduling,
etc.
What this means is that it is not possible (and should not be required) to name your thread as you are not responsible for starting and managing it. That said, for debugging purposes, if you want to provide some name, you should do that to the thread pool itself by setting threadNamePrefix and/or threadGroupName properties.

Java - Get all the implementations of an interface available in client package

I am developing one task scheduler which triggers the tasks in parallel using executor service. I want to make my task scheduler as generic and no code change/less code change in scheduler code base whenever any new type of task is added.
My tasks (mostly client package) can be of any type which basically just accepts particular request and execute the tasks.
To do this I am exposing interface (say ITask) which must be implemented by tasks (which will be on some other app/package) and that will be having one implementation method say example
doTask(IRequest request);
So the use case is if any clients who wants to trigger their job using my scheduler framework/API, just need to add my package in their dependency and rest (those are, getting the list of task classes which implements ITask > schedule it using executor service > retry failed tasks > finally provide the entire tasks status) should be taken care by my schedular API.
What is the optimal way to do this. I am thinking of solution how Junit gets its #Test methods (based on annotation) of client whoever adds Junit dependency in his package, similarly I want get classes based on interface.
You have tagged this question with Spring, but you don't mention anywhere in the question that you are using the Spring framework. This answer makes a few assumptions:
You are using Spring Framework
The implementations of your desired interface have been configured as Spring Beans
If you get access to the ApplicationContext (see the interface ApplicationContextAware), you can use it to look up Spring beans of a certain type. It would look something like this:
Map<String, ITask> beans = appContext.getBeansOfType(ITask.class);
This method returns a map with the key being the bean identifier and the value being the instance of the bean itself. From there, you could loop through the values and add them to your job scheduler.
Alternatively
If you do not want the requirement of having to configure each ITask implementation as a Spring bean, you could use Spring's ClassPathScanningCandidateComponentProvider (a mouthful, I know).
This is a nifty tool that allows you to scan base packages to find bean "candidates". However, in your case, you could use it to find ITask candidates. Clients to your library could configure the base scan packages which you would use to scan:
private String configuredListOfBasePackages;
public void someMethod () {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AssignableTypeFilter(ITask.class));
Set<BeanDefinition> iTaskCandidates = scanner.findCandidateComponents(configuredListOfBasePackages);
// do stuff with the bean definitions
}
This method is obviously a bit more dangerous as it require you to be able to construct a new instance of every candidate you find. As such, this is not the ideal solution.

Sidekiq-like queue using java tools?

I want to have a work queue that behaves almost exactly like ruby's sidekiq(it doesn't need to use Redis, but it can - I just can't use ruby - not even Jruby). Basically I want to be able to create jobs that runs with some parameters and a worker pool executes the jobs. The workers are going to use hibernate to do some work, so I think that Spring integration could make things easier.
Spring Integration has Redis Queue inbound and outbound channel adapters.
The inbound message-driven adapter doesn't currently support concurrency; we worked around that in Spring XD with a composite adapter that wraps a collection of RedisQueueMessageDrivenEndpoint.
Or you could use RabbitMQ; the Spring Integration adapter for it does support concurrency.
EDIT
The bus was extracted to a sub project within that repo.
Spring Framework has ThreadPoolTaskExecutor. You could use it in your class as follows.
#Autowired
ThreadPoolTaskExecutor executor;
ThreadPoolTaskExecutor has properties needed to be set before it is put to use. PostConstruct will be executed after the dependency injections, so we can set the properities of ThreadPoolExecutor there.
#PostConstruct
public void init() {
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
}
Then you can start using executor as follow
executor.execute(new EmailtoCustomerTask("zhw#gmail.com"));
The only requirement needed to become a task is to implement the Runnable interface.
private class EmailtoCustomerTask implements Runnable

looking for persistent timers for a spring application

I'm looking for a lib that allow me to do
define a worker that will be invoked once on a specific time in the future (not need the re-schedule / cron like featrure) i.e. a Timer
The worker should accept a context which withe some parameters / inputs
all should be persistent in the DB (or file) the worker
worker should be managed by spring -- spring should instantiate the worker so it can be injected with dependencies
be able to create timers dynamically via API and not just statically via spring XML beans
nice to have:
support a cluster i.e. have several nodes that can host a worker. each store jobn in the DB will cause invokaction of ONE work on one of the nods
I've examined several alternatives none meets the requirements:
Quartz
when using org.springframework.scheduling.quartz.JobDetailBean makes quartz create your worker instance (and not by spring) so you can't get dependecy ijection, (which will lead me to use Service Locator which I want to avoid)
while using org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean you can't get a context. your Worker expose one public method that accepts no arguments.In addition when using MethodInvokingJobDetailFactoryBean you can't use persistence (form the Javadoc)
Note: JobDetails created via this FactoryBean are not serializable and thus not suitable for persistent job stores. You need to implement your own Quartz Job as a thin wrapper for each case where you want a persistent job to delegate to a specific service method.
Spring's Timer and simple JDK Timers does not support the persistence / cluster feature
I know I can impl thing myself using a DB and Spring (or even JDK) Timers but I prefer to use an a 3r party lib for that.
Any suggestions?
If you want to create the job details to generate triggers/job-details at runtime and still be able to use Spring DI on your beans you can refer to this blog post, it shows how to use SpringBeanJobFactory in conjunction with ObjectFactoryCreatingFactoryBean to create Quartz triggering objects at runtime with Spring injected beans.
For those interested in an alternative to Quartz, have a look at db-scheduler (https://github.com/kagkarlsson/db-scheduler). A persistent task/execution-schedule is kept in a single database table. It is guaranteed to be executed only once by a scheduler in the cluster.
Yes, see code example below.
Currently limited to a single string identifier for no format restriction. The scheduler will likely be extended in the future with better support for job-details/parameters.
The execution-time and context is persistent in the database. Binding a task-name to a worker is done when the Scheduler starts. The worker may be instantiated by Spring as long as it implements the ExecutionHandler interface.
See 3).
Yes, see code example below.
Code example:
private static void springWorkerExample(DataSource dataSource, MySpringWorker mySpringWorker) {
// instantiate and start the scheduler somewhere in your application
final Scheduler scheduler = Scheduler
.create(dataSource)
.threads(2)
.build();
scheduler.start();
// define a task and a handler that named task, MySpringWorker implements the ExecutionHandler interface
final OneTimeTask oneTimeTask = ComposableTask.onetimeTask("my-onetime-task", mySpringWorker);
// schedule a future execution for the task with a custom id (currently the only form for context supported)
scheduler.scheduleForExecution(LocalDateTime.now().plusDays(1), oneTimeTask.instance("1001"));
}
public static class MySpringWorker implements ExecutionHandler {
public MySpringWorker() {
// could be instantiated by Spring
}
#Override
public void execute(TaskInstance taskInstance, ExecutionContext executionContext) {
// called when the execution-time is reached
System.out.println("Executed task with id="+taskInstance.getId());
}
}
Your requirements 3 and 4 do not really make sense to me: how can you have the whole package (worker + work) serialized and have it wake up magically and do its work? Shouldn't something in your running system do this at the proper time? Shouldn't this be the worker in the first place?
My approach would be this: create a Timer that Spring can instantiate and inject dependencies to. This Timer would then load its work / tasks from persistent storage, schedule them for execution and execute them. Your class can be a wrapper around java.util.Timer and not deal with the scheduling stuff at all. You must implement the clustering-related logic yourself, so that only one Timer / Worker gets to execute the work / task.

How to ensure that methods called from same thread use the same DB session

In our system we have multi-threaded processing engine. During processing each thread calls methods to retrieve data from the database. We determined that performance is greatly improved if methods called from the same thread use the same DB session (sessions are coming from the pool of course).
Is there any standard way in Spring to ensure such thing or we have to come up with our own custom solution?
UPDATE: Forgot to mention that same methods can be called in different context where they should use a standard way of getting the session from the pool
I did not see Spring anywhere in your question. So I assume you want a simple utility to do this.
class SessionUtil {
private ThreadLocal currentSession;
public Session getCurrentSession() {
if(currentSession.get() == null) {
Session s = //create new session
currentSession.set(s);
}
return (Session)currentSession.get();
}
}
The Thread local will ensure that within the same thread it is always the same session. If you are using Spring then the classes/utilities mentioned above (in other responses) should be perfect.
Spring has a class called TransactionSynchronizationManager. It stores the current Session in a ThreadLocal. The TransactionSynchronizationManager is not recommended for use by the developer, but you can try using it.
Session session = ((SessionHolder)
TransactionSynchronizationManager.getResource(sessionFactory)).getSession();
(if you are using EntityManager, simply replace "Session" with "EntityManager").
You can have the sessionFactory injected in your bean - it is per-application.
Take a look at this discussion.
Other options, which I think are preferable to manual thread-handling are:
Thread pooling
Spring batch
Spring-JMS integration
Spring 3.0 has a concept of thread-scoped beans (hovewer, this scope is not registered by default, see docs): 3.5 Bean scopes, 3.5.5.2 Using a custom scope
EDIT:
I say about this:
Thread-scoped beans As of Spring 3.0,
a thread scope is available, but is
not registered by default. For more
information, see the documentation for
SimpleThreadScope. For
instructions on how to register this
or any other custom scope, see
Section 3.5.5.2, “Using a custom
scope”.
Spring coordinates database sessions, connections and threads through it's Transaction Framework (actually, using its TransactionSynchronizationManager - see description here - but you really don't want to mess with that directly, it's fearsome). If you need to coordinate your threads, then this is by far the simplest way of doing it.
How you choose to use the framework, however, is up top you.

Categories

Resources