I was handled a design of a threaded application that has the following requirement: It has to have a dynamic number of threads it runs based on the time of day (Peak/off-peak).
I did my homework and researched for the best way to do this, and I found that java has a class named ThreadPoolExecutor:
java.util.concurrent.ThreadPoolExecutor.ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
The two variables in focus here are the corePoolSize, and the maximumPoolSize, both act as the lower and the upper bound of the thread pool along with the workQueue. tuning these values have different strategies and it is advisable to use the executer factory methods instead of the constructor in case these parameters are not needed to be set explicitly.
public class Main {
public static void main(String[] args) {
final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0, 10, 0L, TimeUnit.MILLISECONDS, queue);
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
TimerTask task = new TimerTask() {
#Override
public void run() {
threadPool.setCorePoolSize(1);
threadPool.setMaximumPoolSize(1);
System.out.println("changed");
}
};
new Timer().schedule(task, 10000);
for (int i = 0; i < 400; i++) {
threadPool.submit(new WorkItem(i));
}
}
}
And this is the class that resembles the thread to run
public class WorkItem implements Runnable {
private int workItemNumber;
private long startTime;
public WorkItem(int workItemNumber) {
this.workItemNumber = workItemNumber;
}
#Override
public void run() {
startTime = System.currentTimeMillis();
System.out.println("thread Number: " + workItemNumber + " started at: " + startTime);
while (System.currentTimeMillis() - startTime < 5000) {
}
System.out.println("WorkItem done: " + workItemNumber);
}
}
However, looking at the logs, the number of executed threads remain the same with no change.
Your code is running exactly as you intend it to. 10 threads are started and run, and 100 threads are queued. At that point, your main thread (the one queuing threads) is blocked by the blocking queue. Your timer then changes the available threads to 1, meaning your queue processes even slower. What you are seeing however, is that because your threads have to wait for longer than 10 seconds to actually execute they complete immediately. Try making the following changes to your code:
public class WorkItem implements Runnable {
private long startTime;
private long runTime;
private int workItemNumber;
public WorkItem(long startTime, int workItemNumber) {
this.startTime = startTime;
this.workItemNumber= workItemNumber;
}
#Override
public void run() {
System.out.println("WorkItem started: " + workItemNumber + " Queued at: " + startTime);
runTime = System.currentTimeMillis();
while (System.currentTimeMillis() - runTime < 10000) {
}
System.out.println("WorkItem done: " + workItemNumber);
}
}
This will let you see the execution occurring as you would expect. The strange thing about using an array blocking queue with your core pool set to 0 is that it'll only start a single thread, then fill up the queue, then start more threads (up to max pool size). You can see this happening if you make a subtle change to your queuing code.
for (int i = 1; i < 101; i++) {
threadPool.submit(new WorkItem(System.currentTimeMillis(), i));
}
for (int i = 101; i < 401; i++) {
long thisTime = System.currentTimeMillis();
threadPool.submit(new WorkItem(System.currentTimeMillis(), i));
while (System.currentTimeMillis() - thisTime < 500) {
}
}
You've created a pool with 10 max threads
new ThreadPoolExecutor(0, 10, 0L, TimeUnit.MILLISECONDS, queue);
and you've submitted 400 tasks
for (int i = 0; i < 400; i++) {
threadPool.submit(new Thread(System.currentTimeMillis(), i));
}
The thread pool will not use more than 10 threads (threads represented by the java.lang.Thread class) to execute your tasks.
Submitting and executing all these tasks takes less than the 10000 millisecond delay you've set for your TimerTask
new Timer().schedule(task, 10000, 5000);
Once your TimerTask is run, your pool will only have one thread running and claiming submitted tasks (once the other threads' tasks are completed).
Sample that will show that only one thread will remain in the ThreadPoolExecutor once the TimerTask has been executed (and after any executing tasks finish)
public class Jackson {
public static void main(String[] args) {
final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0, 10, 0L, TimeUnit.MILLISECONDS, queue);
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
TimerTask task = new TimerTask() {
#Override
public void run() {
threadPool.setCorePoolSize(1);
threadPool.setMaximumPoolSize(1);
System.out.println("changed");
this.cancel();
}
};
new Timer().schedule(task, 5, 5000);
for (int i = 0; i < 400; i++) {
threadPool.submit(new WorkItem(i));
}
}
}
class WorkItem implements Runnable {
private int workItemNumber;
public WorkItem(int workItemNumber) {
this.workItemNumber = workItemNumber;
}
#Override
public void run() {
System.out.println("WorkItem #" + workItemNumber + " executing on Thread with name: " + Thread.currentThread().getName());
}
}
Whilst using this on later version of JDK/Grails setting max poolSize reducing it all works well in older versions of grails and JDK7. (Unsure where the problem resides I had to do this)
private static final int actualPoolSize = Holders.grailsApplication.config.maximumPoolSize ?: 3
private static int maxPoolSize = actualPoolSize
public EnhancedExecutor() {
super(maxPoolSize,maxPoolSize,keepAliveTime,timeoutUnit,new PriorityBlockingQueue<Runnable>(maxQueue))
}
public void setMaxPoolSize(int i) {
this.maxPoolSize=i
super.purge()
super.setCorePoolSize(i?:actualPoolSize)
super.setMaximumPoolSize(i?:actualPoolSize)
}
Without the purge I could increase to a higher level without any errors. Attempting to reduce returned a null for i . or actualPoolSize. (did not seem to want to shrink without throwing an exception).
I took on comments from BretC about threads being busy and it appears purge solves that by ensuring all is reset before attempting to reset superValues
It looks like the "Set maximum pool size" method will reduce the number of idle threads only...
public void setMaximumPoolSize(int maximumPoolSize) {
if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
throw new IllegalArgumentException();
this.maximumPoolSize = maximumPoolSize;
if (workerCountOf(ctl.get()) > maximumPoolSize)
interruptIdleWorkers();
}
If threads stay busy, it doesn't look like they are released.
(I could be wrong... It doesn't look like anything magical happens when a thread is finished to clean things up - need to take more of a look...)
Related
I think it's necessary to use AtomicInteger in the ThreadFactory but when I am trying to prove it to myself, I failed hard.
new ThreadFactory() {
private int threadId = 0; <---- AtomicInteger preferred
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("my-thread-" + (threadId++)); <--- dangerous code
return t;
}
}
If several requests come, the thread factory will generate threads to handle them and during the generation, there could be a gap during which a race condition might sneak in.
I tried with the following code to demonstrate my theory, but it's not happening at all with 2_000 core threads.
#Slf4j
public class ThreadFactoryTest {
private ConcurrentHashMap<String, Thread> threadIdThreadMap = new ConcurrentHashMap<>();
private ThreadPoolExecutor myExecutor = new ThreadPoolExecutor(2000, 2000, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100000), new ThreadFactory() {
private int threadId = 0;
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("my-thread-" + (threadId++));
if (threadIdThreadMap.contains(t.getName())) {
log.error("already existed");
System.err.println(myExecutor);
myExecutor.shutdownNow();
} else threadIdThreadMap.put(t.getName(), t);
return t;
}
}, new ThreadPoolExecutor.AbortPolicy());
#Test
public void testThreadFactory() throws Exception {
for (int i = 0; i < 100; ++i) {
new Thread(() -> runOneHundredJobs()).start();
}
Thread.sleep(1000000);
myExecutor.shutdown();
myExecutor.awaitTermination(100, TimeUnit.MINUTES);
}
private void runOneHundredJobs() {
log.info("{} starting to submit tasks", Thread.currentThread().getName());
for (int i = 0; i < 100; ++i) {
myExecutor.execute(() -> {
while (100 < System.currentTimeMillis()) {
try {
Thread.sleep(1000);
if (Math.random() > 0.99) break;
System.out.println(Thread.currentThread().getName());
System.out.println(myExecutor);
} catch (Exception e) {
}
}
} );
}
}
}
Looks like a stupid question since I always know that "it's hard to create the gap for a multi-thread race condition".
Any help/clue will be appreciated ;)
UPDATE
Really thanks for the help along the way, #StephenC and #Slaw. I am sorry that I misunderstood some points there ;(
So newThread should be implemented in a thread-safe way and then in my case, the AtomicInteger is required. And I wanna have a quote from StephenC:
Failure to demonstrate a race condition doesn't mean it doesn't exist.
Is it necessary to use AtomicInteger in a ThreadFactory?
It will depend on how the factory object is used.
If you supply a different factory object to each instance of ThreadPoolExecutor then the (actual) concurrency requirements for the factory will depend on how the executor uses it. In the absence of statements in the javadocs, you would need to examine the source code. I haven't checked, but I suspect that expansion of the thread pool (including the call to newThread) happen inside a mutex. If my suspicion is correct, then this use-case doesn't require the factory object to be thread-safe.
UPDATE - I have now checked, and my suspicion was incorrect (for Java 8 & 12). The newThread call is made when creating a new Worker object, and that is not done while holding a mutex. Therefore, your newThread method needs to be thread-safe in this context too.
If a factory object is shared with other things (e.g. another executor) then you are correct: your newThread method needs to be thread-safe.
I haven't looked at your code to try to show race conditions, but to my mind, that's not the best way to go about this. Code inspection and reasoning is a better way. Failure to demonstrate a race condition doesn't mean it doesn't exist.
I am making the test simpler to make the expected result emerge from under the water.
With the test below, the expected thread size is 1000 sharp while using int will give a less size oftentimes (994, 996, 999 in my macOS), not all the times.
public class ThreadFactoryTest {
private ConcurrentHashMap<String, Thread> threadIdThreadMap = new ConcurrentHashMap<>();
private ThreadPoolExecutor myExecutor = new ThreadPoolExecutor(2000, 2000, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100000), new ThreadFactory() {
private int threadId = 0;
private AtomicInteger atomicThreadId = new AtomicInteger(0);
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("my-thread-" + (threadId++));
// uncomment this line, the thread size will be less than 1000
t.setName("my-thread-" + (atomicThreadId.getAndIncrement()));
threadIdThreadMap.put(t.getName(), t);
return t;
}
}, new ThreadPoolExecutor.AbortPolicy());
#Test
public void testThreadFactory() throws Exception {
for (int i = 0; i < 50; ++i) {
new Thread(() -> runOneHundredJobs()).start();
}
Thread.sleep(1000000);
myExecutor.shutdown();
myExecutor.awaitTermination(100, TimeUnit.MINUTES);
}
private void runOneHundredJobs() {
for (int i = 0; i < 20; ++i) {
myExecutor.execute(() -> {
while (100 < System.currentTimeMillis()) {
try {
Thread.sleep(1000);
log.warn("count: {}", threadIdThreadMap.size());
} catch (Exception e) {
}
}
});
}
}
}
I'm looking to create a ScheduledThreadPoolExecutor with an unknown pool size. Pool size is determined at run-time, will likely be between 1-5, and for this example I used size 2. We use a custom Task that simply executes a method every so often, but that method will eventually throw an exception (which I've simulated with a simple numTimes variable and if statement). If an exception is thrown, I only want to cancel execution of THAT specific thread! If all threads are cancelled, I want to shut down the ScheduledThreadPoolExecutor. Once numTimes == 5 I simulate the exception to cancel the thread), and I can manage to cancel the thread a number of ways but they just don't feel right.
As a side note, I placed ScheduledFuture everywhere just to play around with cancelling it.
public class Test
{
static ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2);
public static void main(String[] args)
{ stpe.scheduleWithFixedDelay(new UpdateTask(1), 0, 1000, TimeUnit.MILLISECONDS);
stpe.scheduleWithFixedDelay(new UpdateTask(2), 0, 5000, TimeUnit.MILLISECONDS);
// stpe.shutdown();
}
public static class UpdateTask implements Runnable
{
int id;
int numTimes = 0;
ScheduledFuture<?> t;
public UpdateTask(int id)
{ this.id = id;
}
public void run()
{ System.out.println("Hello " + id + " num: " + numTimes);
String fn = "C:\\lib" + id;
if (numTimes++ == 5)
{ File f = new File(fn);
f.mkdir();
t.cancel(false);
}
}
}
}
Calling t.cancel() from run() or from main() have the same effect, in that the thread stops executing but the program does not stop running. Naturally, this is because the ThreadPoolExecutor is still doing stuff, despite both threads no longer being scheduled.
I tried invoking shutdown on stpe, but it doesn't finish thread execution. Two directories are created with stpe.shutdown commented out, and they are not otherwise.
I can't figure out an elegant way to cancel ScheduledFuture, then ScheduledThreadPoolExecutor when all ScheduledFuture's are cancelled.
Final approach ##
I was not able to get s1.get() to work as described in the answer below, so I simply created my own class to handle it.
public class Test
{
static ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2);
static CancelUpdateTasks canceller;
public static void main(String[] args)
{ Test t = new Test();
canceller.add(0, stpe.scheduleWithFixedDelay(new UpdateTask(0), 0, 1000, TimeUnit.MILLISECONDS));
canceller.add(1, stpe.scheduleWithFixedDelay(new UpdateTask(1), 0, 5000, TimeUnit.MILLISECONDS));
canceller.waitForSchedules();
stpe.shutdown();
}
public Test()
{ canceller = new CancelUpdateTasks();
}
public static class UpdateTask implements Runnable
{
int id;
int numTimes = 0;
public UpdateTask(int id)
{ this.id = id;
}
public void run()
{ System.out.println("Hello " + id + " num: " + numTimes);
if (numTimes++ == 5)
{ canceller.cancel(id);
}
}
}
public class CancelUpdateTasks
{ List<ScheduledFuture<?>> scheduler;
boolean isScheduled;
public CancelUpdateTasks()
{ scheduler = new ArrayList<ScheduledFuture<?>>();
isScheduled = false;
}
public void waitForSchedules()
{ int schedId = 0;
while(isScheduled)
{ ScheduledFuture<?> schedule = scheduler.get(schedId);
if (schedule.isCancelled())
{ if (schedId == scheduler.size() - 1)
return;
schedId++;
}
else
{ try
{ Thread.sleep(1000);
}
catch (InterruptedException e)
{ e.printStackTrace();
}
}
}
}
public void add(int id, ScheduledFuture<?> schedule)
{ scheduler.add(id, schedule);
if (!isScheduled)
isScheduled = true;
}
public void cancel(int id)
{ scheduler.get(id).cancel(false);
}
public void cancelNow(int id)
{ scheduler.get(id).cancel(true);
}
}
}
You'll want to issue a shutdown on the pool. The JVM will continue to run until there are only daemon threads alive. A ThreadPoolExecutor by default will create non-daemon threads.
Just invoke stpe.shutdown();
edit: Based on OPs update
shutdown admittedly is different for ScheduledThreadPoolExecugtor than a plain ThreadPoolExecutor. In this case shutdown prevents any scheduled task to become re scheduled. To make it work correctly you will have to wait on the futures completion. You can do so by get()ing on the ScheduledFuture
ScheduledFuture sf1 = stpe.scheduleWithFixedDelay(new UpdateTask(1), 0, 1000, TimeUnit.MILLISECONDS);
ScheduledFuture sf2 = stpe.scheduleWithFixedDelay(new UpdateTask(2), 0, 5000, TimeUnit.MILLISECONDS);
sf1.get();
sf2.get();
stpe.shutdown();
In this case both tasks are run asynchronously, the main thread will first wait for sf1 to complete then will wait for sf2 to complete and finally shutdown.
How would I have this method run every couple of seconds in a recursive function.
I want the i variable to update by 1 every couple of seconds than print it to the console.
In javascript I could use setTimeout is there a method like the javascript setTimeout in Java?
final i = 0;
public void timerActions() {
i = i + 1;
System.out.println(i);
}
try with Timer
Timer timer = new Timer("Display Timer");
TimerTask task = new TimerTask() {
#Override
public void run() {
timerActions();
}
};
// This will invoke the timer every second
timer.scheduleAtFixedRate(task, 1000, 1000);
}
You should use ScheduledExecutorService for that.
Update per Peter Lawrey comment (thanks):
Methods :
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
and
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
can be used in order to achieve your desired behavior.
You can put the Thread to sleep after execution if it's just a simple application which just has to "run slower".
For example:
final i = 0;
public void timerActions() {
i++;
System.out.println(i);
Thread.sleep(1000);
}
1000 in the parentheses means 1000ms=1second - the amount of time in which the thread sleeps.
This is a simple way to do it, but be aware that in larger multi-threaded applications you have to take into acount thread safety and related problems.
Documentation for Thread.sleep()
public class TimedAction
{
public static void main(String[] args) throws Exception
{
System.out.println("begin");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable command = new Runnable()
{
private int i = 0;
#Override
public void run()
{
// put your logic HERE
System.out.println(i++);
}
};
// execute command, immediately (0 delay), and every 2 seconds
executor.scheduleAtFixedRate(command, 0, 2, TimeUnit.SECONDS);
System.in.read();
executor.shutdownNow();
executor.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("end");
}
}
This will print "Counting..." on every 2 seconds
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
private int counter = 0;
public void run() {
counter++;
if (counter <= 3) {
System.out.println("Counting - counter = " + counter);
} else {
System.out.println("Stopping timer execution");
this.cancel();
}
}
public static void main(String[] args) {
Timer timer = new Timer("TimerThreadName");
MyTimerTask task = new MyTimerTask();
// void java.util.Timer.schedule(TimerTask task, long delay, long period)
timer.schedule(task, 0, 2000);
}
}
I'm new to the #Schedule annotations in J2EE6
I want to run a job using EJB 3.x with Glassfish 3.1.
The javax.ejb.Schedule seems to be a good choice for us, so we could think of our custom time as something like:
#Singleton
public class CustomTimer {
#EJB
SettingsFacade settingsFacade;
#Schedule(second="someSecondParameter", minute="someMinuteParameter",hour="someHourParameter", persistent=false)
public void executeTimer(){
//Code executing something against database using the settingsFacade
}
}
Here, we want the parameters to be got from database, so they are changed every month. Any clean solution for this?
#Singleton
#Startup
public class ScheduleTimerService {
#Resource private TimerService timerService;
public void setTimerService(TimerService timerService) {this.timerService = timerService; }
#PostConstruct
private void postConstruct() {
timerService.createCalendarTimer(createSchedule());
}
#Timeout
public void timerTimeout(Timer timer) {
Add your code here to be called when scheduling is reached...
in this example: 01h:30m every day ;-)
}
private ScheduleExpression createSchedule(){
ScheduleExpression expression = new ScheduleExpression();
expression.dayOfWeek("Sun,Mon,Tue,Wed,Thu,Fri,Sat");
expression.hour("01");
expression.minute("30");
return expression;
}
}
No, there is no solution with #Schedule, because annotation attributes in general should be compile time constants.
When more flexibility is needed, programmatic timers can be used.
Also then polling database for changed configuration and removing existing and creating new timers must be implemented.
Well You need to created Two Scheduler
One Scheduler will run to update data from Database
Based On that You Can created Other Scheduler.
But for this Need to do it some what programmatic.
You also can see EJB Timers for the same what will help you in this case. which is also annotation based.
There is a simple way of doing this. I wanted to something that called a process every day but, the job itself should be done randomly over the same day. I managed to do that by adding a simple thread worker to run after the EJB timer service has been called. Then I would put it to sleep for a random amount of time during that day.
The following code is an example of a service that wakes up every 1 minute and waits for a thread to finish.
#Schedule(minute = "*/1", hour = "*", persistent = false)
public void runEveryMinute() throws InterruptedException {
log.log(Level.INFO, "Scheduling for every minute .. now it's: " + new Date().toString());
// Delay, in milliseconds before we interrupt adding a follower thread
//we can therefore garantee that it runs every day
long patience = 1000 * 5;
threadMessage("Starting forever alone no more thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for new thread to finish");
// loop until MessageLoop thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second for MessageLoop thread to finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting! Adding new followers now!");
t.interrupt();
// Shouldn't be long now -- wait indefinitely
t.join();
}
}
threadMessage("Finally! You are not alone anymore!");
}
// Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = {
"A kid will eat ivy too"
};
try {
for (int i = 0;
i < importantInfo.length;
i++) {
// Pause for 4 seconds
int max = 10;
int min = 2;
int randomTimer = 0 + (int) (Math.random() * ((max - min) + 1));
Thread.sleep(randomTimer * 1000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("Patience is not a virtue! Thread stopping for now!");
}
}
}
using JConsole it seems i get a deadlock situation when 2 threads try to modify this object.
package com.steven.concurrent.assignment2.memoryallocator;
/*
* This seems to deadlock... cant see why though.
*/
public class MemAllocMonitor implements IMemoryAllocator {
private final int MAX_FREE = 50;
private int freePages = MAX_FREE;
//I think this would work, without even the need for sync blocks.....
// But only in the situaion where i would not have to check the bounds of the updates. If it was just modification, this would be
// fine....
//private volatile int freePages = 50;
public MemAllocMonitor(int pages){
assert(pages < MAX_FREE);
this.freePages = pages;
}
public MemAllocMonitor(){
}
#Override
public synchronized void request(int number) {
if(number < 0)
throw new IllegalArgumentException();
while(freePages - number < 0) {
System.out.println("No space....waiting...");
try {
this.wait();
} catch (Exception e) {}
}
freePages -= number;
System.out.println("Requested : " + number + " remaining " + freePages);
this.notifyAll();
}
#Override
public synchronized void release(int number) {
if(number < 0)
throw new IllegalArgumentException();
while(freePages + number > MAX_FREE) {
System.out.println("page table full....would be " + (number + freePages) );
try {
this.wait();
} catch (Exception e) {}
}
freePages += number;
System.out.println("Released : " + number + " remaining " + freePages);
this.notifyAll();
}
#Override
public int getFreePages() {
return freePages;
}
}
This object is accessed via a simple wrapper that implements runnable, and calls either method as shown below.
package com.steven.concurrent.assignment2.memoryallocator;
import concurrent.RandomGenerator;
import concurrent.Time;
public class MemAllocRequester implements Runnable, MemoryAllocatorAction{
private IMemoryAllocator memoryAllocator;
private volatile boolean shutdown = false;;
public MemAllocRequester(IMemoryAllocator memAlloc){
this.memoryAllocator = memAlloc;
}
#Override
public void run() {
while(!shutdown){
Time.delay(500);
memoryAllocator.request(RandomGenerator.integer(0, 30));
}
}
public void ShutDown(){
this.shutdown = true;
}
}
and
package com.steven.concurrent.assignment2.memoryallocator;
import concurrent.RandomGenerator;
import concurrent.Time;
public class MemAllocReleaser implements Runnable, MemoryAllocatorAction{
private IMemoryAllocator memoryAllocator;
private volatile boolean shutdown = false;;
public MemAllocReleaser(IMemoryAllocator memAlloc){
this.memoryAllocator = memAlloc;
}
#Override
public void run() {
while(!shutdown){
Time.delay(500);
memoryAllocator.release(RandomGenerator.integer(0, 30));
}
}
public void ShutDown(){
this.shutdown = true;
}
}
It is started off as such...
package com.steven.concurrent.assignment2.memoryallocator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MemAllocMain {
public static void main(String[] args){
ExecutorService executor = Executors.newFixedThreadPool(10);
//IMemoryAllocator memoryAllocator = new MemAllocSemaphore();
IMemoryAllocator memoryAllocator = new MemAllocMonitor();
System.out.println("Starting app with " + memoryAllocator.getFreePages() + " pages...");
Thread t1 = new Thread(new MemAllocRequester(memoryAllocator));
Thread t2 = new Thread(new MemAllocReleaser(memoryAllocator));
t1.setName("MEMORY REQUESTER £££££££££££££££££££");
t2.setName("MEMORY RELEASER £££££££££££££££££££");
executor.submit(t1);
executor.submit(t2);
}
}
I have implemented a solution using the semaphore class, but for some reason this is causing trouble using the default java monitor solution. It runs for about 30 seconds, then both threads go into their waiting state, even though the lock should be enforced.
The problem is that both threads are hitting the upper and lower bounds (50 and 0 respectively) at the same time. Both examples below highlight the deadlock.
Scenario 1
request(29) - freePages=21
request(30) - under 0 so waits
release(30) - over 50 so waits : deadlock
Scenario 2
request(29) - freePages=21
release(30) - over 50 so waits
request(30) - under 0 so waits : deadlock
I am not sure what the exact requirements are for the homework problem but you need to revisit the release and request methods. I see two viable solutions:
Change the release method so that it only releases up to MAX_FREE but will still return
Change the release method so that it can release a subset of the amount requested, notifyAll, reenter the wait so it can release the remaining amount.
Also, you are kind of using the ExecutionService wrong. The ExecutionService is what creates the Threads so there is no reason for you to create the threads like you are doing.
Thread t1 = new Thread(new MemAllocRequester(memoryAllocator));
Thread t2 = new Thread(new MemAllocReleaser(memoryAllocator));
The threads you are creating will actually never be 'started' as Threads. It is still working for you because the ExecutionService threads will call your Thread.run() which will call MemAlloc*.run(). i.e. your t1 and t2 threads just pass the run() call along and provide no value.
Your MemAllocRequester and MemAllocReleaser are Runnables so just pass those into the ExecutionService directly.
executor.submit(new MemAllocRequester(memoryAllocator));
executor.submit(new MemAllocReleaser(memoryAllocator));