java concurrency - singleton design with a monitor thread - java

I have a singleton class thus
public final class HandlerCache {
//the cache maintains a handler per thread
private final Map<Thread, Handler> cache = new ConcurrentHashMap<>();
private final Thread monitor;
private static final HandlerCache INSTANCE = new HandlerCache();
private HandlerCache() {
monitor = new Thread() {
//periodically monitor cache and close handlers when a thread has died
}
monitor.start()
}
public static HandlerCache getInstance() {
return INSTANCE;
}
public Handler getHandler() throws Exception {
final Thread thread = Thread.currentThread();
Handler handler = cache.get(thread);
if (!(handler == null))
return handler;
handler = HandlerFactory.get(getHandlerFromName(thread.getName()));
cache.put(thread, handler);
return handler;
}
}
I am leaking the singleton instance to the monitor thread before the constructor is finished, what is the better way ?
Will making cache volatile will fix the issue ?

As mentioned by user2677485, you should be using a ThreadLocal and implement the initialValue method. The other point is that the Handler implementation should implement the finalize method so that when it is being reclaimed by the GC this method will be called and you can clean up your resources.
The code can be simplified as something like the following:
public class HandlerCache {
private static final handlers = new ThreadLocal<Handler>() {
protected Handler initializeValue() {
return HandlerFactory.get(...);
}
};
public static Handler getHandler() {
return handlers.get();
}
}

Rather than starting the thread within the HandlerCache constructor, you could initialize the instance using a static function that would first construct the HandlerCache and then start the thread.

Related

thread safety AbstractRoutingDataSource with spring-boot

how to use Multiple database connection on multiple threads..
I know how to use database connection with routingdataSource dynamically
but I think it is not thread safety Because the class is static.!!!
// first thread
ContextHolder.set("firstId");
mapper.select();
ContextHolder.clear(idFirst);
// second thread
ContextHolder.set("secondId");
mapper.select();
ContextHolder.clear(idFirst);
public class ContextHolder {
private static ThreadLocal<String> CONTEXT = new ThreadLocal<>();
public static void set(String dbType) {
CONTEXT.set(dbType);
}
public static String getClientDatabase() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
like this code.
public class Poller implements Runnable {
#Override
public List<Map<String, Object>> getNext() {
Map<String, Object> params = new HashMap<>();
ContextHolder.set(dbConnectionId);
List<Map<String, Object>> list = blogMapper.findAll(params)
ContextHolder.clear();
return list;
}
....
}
the
private static ThreadLocal<String> CONTEXT = new ThreadLocal<>();
create a threadlocal variable. It means that what you put inside is bound to a specific thread and when you get something it is what in this thread that is returned.
For instance, in thread 1 you set:
CONTEXT.set(1);
in thread 2 you set:
CONTEXT.set(2);
and later thread print what inside with a
CONTEXT.get();
it will print 1 for thread 1 and 2 for thread 2.
So now, if you use a standard synchronous model, it is fine as long as you don't forget to clean the value when you enter and/or exit the request.
As soon as you use async (reactive, executor, ...) it will fail as part of your process will be run on another thread.

Observer pattern and data synchronization in Android

I want to implement the observer pattern in Android. The observable and observers have to work in their own threads (HandlerThread). The observable object produces some results and notifies their observers every milliseconds. The observers register by passing themselves and Handler reference as arguments.
Example code:
public class Observable {
public interface Observer {
void notify(List<Object> results);
}
private HandlerThread handlerThread;
private List<Object> results = new ArrayList<>();
private final Map<Observer, ObserverWrapper> observers = new HashMap<>();
private void working() {
//Critial section...
//modifying results list...
synchronized (observers) {
for (ObserverWrapper wrapper : observers.values()) {
wrapper.notify(results);
}
}
}
public void register(Observer observer, Handler handler) {
synchronized (observers) {
//Create observer wrapper and add to map here...
}
}
public void unregister(Observer observer) {
synchronized (observers) {
//Remove observer from the map...
}
}
private static final class ObserverWrapper {
private final Observer observer;
private final Handler handler;
public ObserverWrapper(Observer observer, Handler handler) {
this.observer = observer;
this.handler = handler;
}
public void notify(final List<Object> results) {
//The observable thread
handler.post(new Runnable() {
void run() {
//The observer thread
//Critical section...
observer.notify(results);
}
});
}
}
}
The question is: how to synchronize results list that is passed to all observers? I cannot use a copy for each observer because it would cause high memory usage.
There are three options I can think of:
Use the results object as a monitor. That requires minimum changes but this a) not very clean as object itself doesn't say anything about being a monitor. b) Given that the updates are coming every few milliseconds, there is a concern that observer threads will be locking the producer thread for extended periods of time. Both producer and the observer will have to:
synchronized(results) {
// ...
}
Pass an explicit lock object to notify() and use it explicitely:
private final Object lock = new Object();
synchronized(lock) {
// Update results
}
...
synchronized(lock) {
// Read results
}
You mentioned that you don't want to copy results to reduce GC footprint, but this can be the most concurrent option. I'd do it if I were writing it. There is actually a better option, more optimistic option in terms of memory, which is CopyOnWriteArrayList, it will only copy if there is a simultaneous read and write:
https://developer.android.com/reference/java/util/concurrent/CopyOnWriteArrayList.html
Based on the discussions, here is the most concurrent way to do it:
private void working() {
//Critial section...
//modifying results list...
// Create a copy for observers to process
List resultsToProcess = new ArrayList(results);
synchronized (observers) {
for (ObserverWrapper wrapper : observers.values()) {
wrapper.notify(resultsToProcess);
}
}
}

What is the scope of "this" when calling a method from an individual thread?

I am writing a small Java class to act a heartbeat for a project. The class is fairly simple. I have a public class called HeartbeatServer.class that contains to private classes which both implement Runnable.
The heartbeat and listener thread will both use the same DatagramSocket which I created outside of the scope of both thread classes and declared it volatile so both threads can access it.
My question is regarding my thread classes. In the thread classes if I call HeartbeatServer.this.serverSocket what is the scope of this? My concern is I don't want each thread to use a different version of HeartbeatServer since I have to bind the DatagramSocket to a specific IP address and port.
Is what I am doing correct to get the result I am looking for? I want both threads to have access to the same DatagramSocket that was created by the constructor of the HeartbeatServer class.
Here is my code.
public volatile DatagramSocket serverSocket;
private Map<String, InetSocketAddress> registeredClients = new HashMap<String, InetSocketAddress>();
public volatile Boolean running = true;
public HeartbeatServer() throws SocketException{
serverSocket = new DatagramSocket(null);
}
** Other methods would go here **
// This is the thread that will send the heartbeats back to the client.
private class HeartbeatThread implements Runnable {
#Override
public void run() {
while (HeartbeatServer.this.running) {
HeartbeatServer.this.sendData();
}
}
}
// This is the thread that will listen for clients connecting to the server.
private class ListenerThread implements Runnable {
#Override
public void run() {
while (HeartbeatServer.this.running) {
HeartbeatServer.this.recieveData();
}
}
}
** NOTE **
My code is not done, so things might not make any sense in the current context.
If you need HeartbeatServer to be unique you should make the HeartbeatServer Singleton. Please check here for more details.
Simply
public class HeartbeatServer {
private static HeartbeatServer heartbeatServer;
// Disable object creation from other classes
private HeartbeatServer () {
}
public static HeartbeatServer getInstance() {
if(heartbeatServer == null)
heartbeatServer = new HeartbeatServer();
return heartbeatServer;
}
}
What you are doing is, your thread object is using the enclosing parent. Which is not recommended.
If you want to make sure the HeartBeatServer instance you get is the right one, you could add a constructor to the internal runnables, along the lines of
private class HeartbeatThread implements Runnable {
private HeartbeatServer server;
HeartBeatThread(HeartbeatServer theServer) {
this.server = theServer;
}
#Override
public void run() {
while (server.running) {
server.sendData();
}
}
}

ThreadPoolExecutor and Android's thread priority

I'd like to make a ThreadPollExecutor that executes tasks with a given priority Process.setThreadPriority(int).
How should I do it? Adding the call to setThreadPriority at the start of each runnable sent to the thread poll? I've also considered using a custom thread factory like this:
private final static class ProcessPriorityThreadFactory implements ThreadFactory {
private final int threadPriority;
public ProcessPriorityThreadFactory(int threadPriority) {
super();
this.threadPriority = threadPriority;
}
#Override
public Thread newThread(Runnable r) {
return new Thread(new PriorityChangeWrapper(r, threadPriority));
}
private final static class PriorityChangeWrapper implements Runnable {
private final Runnable originalRunnable;
private final int threadPriority;
public PriorityChangeWrapper(Runnable originalRunnable, int threadPriority) {
super();
this.originalRunnable = originalRunnable;
this.threadPriority = threadPriority;
}
#Override
public void run() {
Process.setThreadPriority(threadPriority);
originalRunnable.run();
}
}
}
What is the best solution for this problem? Thanks
The custom factory as given in your question is the correct way to do this. The factory pattern is used for just this reason as it gives you total control over all the threads created by the ExecutorService. (For example you can also change the thread names etc).
Your implementation of the factory is much more complex than is needed though, all you need is:
private final static class ProcessPriorityThreadFactory implements ThreadFactory {
private final int threadPriority;
public ProcessPriorityThreadFactory(int threadPriority) {
this.threadPriority = threadPriority;
}
#Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setPriority(threadPriority);
return thread;
}
}

Java Executors and per-thread (not per-work unit) objects?

I have a task that would benefit from the Thread Pool design pattern (many small tasks to be performed in parallel). I initially implemented a naive thread pool from scratch, with n Runnables all pulling work units from the same ConcurrentLinkedQueue until the queue is empty, then terminating. I then decided "hey, let's try the Executor in Java, because that is probably better-tested and more reliable than my naively designed system." Problem: in my implementation, each thread persisted until the queue was empty, using a while (!queue.isEmpty()), and got its own instance of a non-threadsafe object, let's call it SlowObject foo, that is time-consuming to construct. Trying to pass all Runnables that go into the Executor's pool an instance of the time-inefficient object fails because it is not thread-safe. Creating a new instance of SlowObject for each Runnable is undesirable because they are costly to construct.
Is there a way to say "how many threads are we using? Let's create one SlowObject for each thread, and then let the Runnables detect what thread we're on and look up the correct object to use?" This sounds brittle and failure-prone -- not sure what design pattern I should be looking at instead, though.
You're better off using a resource pool. Use something like this:
public class SlowObjectPool {
private static final int POOL_SIZE = 10;
private BlockingQueue<SlowObject> slowObjectQueue = new ArrayBlockingQueue(POOL_SIZE);
public SlowObjectPool() {
for (int i = 0; i < POOL_SIZE; i++) {
slowObjectQueue.put(new SlowObject());
}
}
public SlowObject take() throws InterruptedException {
return slowObjectQueue.take();
}
public void release(SlowObject slowObject) {
// TODO You may want to log a warning if this is false
slowObjectQueue.offer(slowObject);
}
}
You may want to make this a singleton as well. Then in your runnables:
public class MyRunnable implements Runnable {
private SlowObjectPool pool;
public MyRunnable(SlowObjectPool pool) {
this.pool = pool;
}
#Override
public void run() {
// The next line blocks until a SlowObject is available
SomeObject someObject = null;
try {
someObject = pool.take()
// Do something with someObject
} catch (InterruptedException ex) {
// Thread is being ended, allow to end
} finally {
if (someObject != null)
pool.release(someObject);
}
}
}
This will create the objects all at once when the pool is first created instead of creating them dynamically, that way none of your runnables have to wait for SomeObject instances to be created.
Java provides the concept of a ThreadLocal variable.
You can use it within your Runnable like this.
public class MyJob implements Runnable {
private static final ThreadLocal < SlowObject > threadLocal =
new ThreadLocal < SlowObject > () {
#Override protected SlowObject initialValue() {
// construct and return your SlowObject
}
};
public void run() {
// work with threadLocal.get()
}
}
Thereby for each thread running your Runnable only a single instance of your class SlowObject is created.

Categories