WakeLock.acquire takes long time on Samsung Galaxy SII LTE - galaxy

In my project, another thread will be launched in the service. To avoid this thread be paused when device suspend, I acquired the WakeLock before launch this thread and release this WakeLock after this thread is finished.
Sometimes, This API call (WakeLock.acquire) takes too long time, over 4 minutes on Samsung Galaxy SII LTE.
Below is my code:
In service onStartCommand, acquire wake lock:
if (mWakeLock == null) {
final PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Eca Engine");
mWakeLock.setReferenceCounted(false);
}
if (!mWakeLock.isHeld()) {
Log.d(TAG, "Before acquire");
mWakeLock.acquire();
Log.d(TAG, "After acquire");
}
......
In thread, release wake lock:
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
the log: "After acquire" printed after "Before acquire" over 4 minutes.
The test device information is:
Model number: Sc-03d
Android version: 2.3.6
Based version: 3c03domlb9
Kernel version: 2.6.35.11 - 3c03domlb9 980106 se.infra#sep-53#2
Build number: gingerbread omlb9
Did any one meet this issue before? Or any suggest for me is appreciated.

I have fixed this problem.
I send a command to the main thread to let it release wake lock instead of release it directly in the new thread. Then this issue can't reproduce anymore.
Does anyone understand the root cause? Why we can not acquire the wake lock in service main thread and release it in another thread even we operate on the same WakeLock obj.

Related

How to ensure thread is not terminated before finalizer completes

I have an unmanaged class that is running a message loop for a child Win32 window. When the program goes to close, it starts the finalizer for the managed class that holds the unmanaged reference to this class. Because another thread is dependent on this class, I need the finalizer to wait until the message loop thread has completed a loop and exits and terminates. However, the timeout loop I have apparently takes too long for the GC finalizer thread or the main thread terminates destroying the entire process.
Is there a way to tell the GC to not timeout a thread for finalizers? I.E. - I need the finalizer thread to block for a little while in the finalizer so it can complete terminating the message loop thread and then release the unmanaged resource.
Here is my finalizer so you get an idea of what's going on:
PONms::NestedWin32::
!NestedWin32()
{
if (msgLoop->IsAlive)
{
winProcess->EndThread(); // blocks and waits for message loop thread to terminate
// and GC apparently doesn't like this causeing the
// entire process to terminate here.
}
if (childHandle != nullptr)
{
DestroyWindowCore(childHandle);
}
if (winProcess != nullptr)
{
delete winProcess; // memory leak due to resource not being released
}
}
I'm thinking I went about this the wrong way, just expecting the code to behave properly and the finalizer to complete.
Here is the simple method I use to poll the other thread to see if it has terminated:
void PONms::NestedWin32UM::
EndThread()
{
int timeOut = 5000;
threadContinue = false;
SendNotifyMessage(childWin, WM_CLOSE, 0, 0);
while (threadActive && timeOut > 0)
{
POCPP::Threading::SleepThreadOne();
timeOut--;
}
}
int timeOut = 5000;
That is a pretty drastic mismatch with the default CLR policy for the finalizer thread timeout. You've got 2 seconds to get the job done. Roughly 10 billion instructions on a modern processor. We can't see what SleepThreadOne() does, but Sleep(1) doesn't sleep for 1 millisecond. Default sleep granularity is 15.625 msec so you'll end up waiting for as long as 78 seconds.
Technically you can extend the timeout by custom-hosting the CLR, ICLRPolicyManager::SetTimeout() method, OPR_FinalizerRun setting. But, realistically, if you can't hack it with 10 billion instructions then extending it isn't very likely to bring relief.
Debugging this isn't that simple, those 2 seconds are over in a hurry. Look at structural fixes. Don't use a bool to synchronize code, use an event (CreateEvent winapi function). And WaitForSingleObject() with a timeout to wait for it to be set. Use 1000 msec max so you give the finalizer thread enough breathing room. And don't be too nice asking the message loop to quit, WM_CLOSE is far too friendly. Code is apt to respond to it with a "Save changes?" message box, that's a guaranteed fail. Use PostQuitMessage(). Or don't bother at all, programs should terminate through the UI and you seem to need to pull the rug another way.

Thread "WebContainer : 0" (00000029) has been active for 647279 milliseconds and may be hung

I am getting the following exception in WebSphere while trying to generate an excel report using jasper.
ThreadMonitor W WSVR0605W: Thread "WebContainer : 0" (00000029) has been active for 647279 milliseconds and may be hung. There is/are 1 thread(s) in total in the server that may be hung.
Tried increasing the default thread pool size from 20 to 50
and also increased WebContainer pool size from 50 to 150. Not worked.
Any solution for this.
Your error message tells that the thread named “ WebContainer : 0” has been doing something for 647 seconds or 10.7 minutes and 1 thread active in the JVM that my also hung (been active for longer than the threshold time).
A hung thread is a thread in Java EE apps which is being blocked by a call or is waiting on a monitor for a locked object to be released, so that the thread can use it. A hung thread can result from a simple software defect (such as an infinite loop) or a more complex cause (for example, a resource deadlock). CPU utilization for that server's java process may become high and unresponsive if number of threads grows.
There are ways to increase the hangtime (default 10min), but not recommended. You have optimize or limit your excel report generation process. I think, Report you are extracting is very big or hitting the db more for generation, basically might be due to code bug. Increasing the number of thread pool has nothing to do for your issue.
In sysout.log: Below lines to the posted warning message, should give some idea about the Java EE class causing this issue. FFDC also helps this to figure it out.
The hang detection option is turned on by default. You can configure it to accommodate the environment, so that potential hangs can be reported. When a hung thread is detected, WAS notifies you so that you can troubleshoot the problem.
Using the hang detection policy, you can specify a time that is too long for a unit of work to complete. The thread monitor checks all managed threads including Web container threads.
From the administrative console, click Servers > Application Servers > server_name
Under Server Infrastructure, click Administration > Custom Properties & Click New.
Add the following properties:
Name: com.ibm.websphere.threadmonitor.interval
Value: The frequency (in seconds) at which managed threads in the selected application server will be interrogated.
Default: 180 seconds (three minutes).
Name: com.ibm.websphere.threadmonitor.dump.java
Value: Set to true to execute the dumpThreads function when a hung thread is detected and a WSVR0605W message is printed. The threads section of the javacore dump can be analyzed to determine what the reported thread
Default: false (0).
Name: com.ibm.websphere.threadmonitor.threshold
Value: The length of time (in seconds) in which a thread can be active before it is considered hung. Any thread that is detected as active for longer than this length of time is reported as hung.
Default: The default value is 600 seconds (ten minutes).
Name: com.ibm.websphere.threadmonitor.false.alarm.threshold
Value: The number of times (T) that false alarms can occur
before automatically increasing the threshold. It is possible that a
thread that is reported as hung eventually completes its work,
resulting in a false alarm. A large number of these events indicates
that the threshhold value is too small. The hang detection facility can
automatically respond to this situation: For every T false alarms, the
threshold T is increased by a factor of 1.5. Set the value to
zero (or less) to disable the automatic adjustment. (Link to
Detecting hung threads in J2EE applications for information on false alarms)
Default: 100
To disable the hang detection option, set the com.ibm.websphere.threadmonitor.interval property to less than or equal to zero.
Save & Restart the WAS instance
This is not an Exception. As you can see it has W level, which is Warning (ThreadMonitor W WSVR0605W). It just informs you that your report generation is extremely long. Longer than 647279 milliseconds. When you will look further down the log, you will most likely notice similar message telling that your thread has finished the job, and is no longer hanged.
Increasing WebContainer pool has nothing to do with that. You have to look at class creating your report and see, if you can make it quicker.
Another solution would be to just handle the report creation as async task using either Async Beans or JMS (you unfortunately are on v7, so no EJB 3.1 or async servlets are available), store it into database or file system and later retrieve using separate request, when the report is done.
In my team we found that Websphere 8.5.5.13 never shuts down the hung threads, so our team came with a solution for a transactional system which process high number of concurrent threads, so instead of hung forever we found a solution using Java 8 that times out after a parameter setting.
Below code shows a demo of how to write a Function that executes critical arbitrary code with timeout.
public class MyFactory
{
TimeUnit timeUnit=TimeUnit.MILLISECONDS;
int REQUEST_TIMEOUT=50;
int MAX_THREADS=1;
ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
public Function<Supplier<?>, ?> executeWithTimeout = typeSupplier-> {
final ExecutorService singleCallableExec =
Executors.newSingleThreadExecutor();
try
{
return executor.submit(()-> {
try { return singleCallableExec.submit(()->{
return typeSupplier.get();
}).get(REQUEST_TIMEOUT, timeUnit);
}
catch (Exception t2) { singleCallableExec.shutdownNow(); throw t2; }
finally {
Optional.of(singleCallableExec)
.filter(e -> !e.isShutdown())
.ifPresent(ExecutorService::shutdown);
}
}).get();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
};
so this can be put into a factory class and call this by every thread requiring to execute critical code which may timeout forever, this will be useful to send a timeout exception which raises an alerts instead of waiting for system to go out of resources
public static void main (String args[])
{
MyFactory mf=new MyFactory();
try
{
long result = (long) mf.executeWithTimeout.apply(()->mf.longCalculation());
System.out.println("Result:" + result);
}
catch (Exception te)
{
if (te instanceof RuntimeException &&
te.getCause() != null && te.getCause() instanceof ExecutionException
&& te.getCause().getCause() != null && te.getCause().getCause()
instanceof TimeoutException)
{
System.out.println(new Date() + " Raising alarm, TimeoutException");
}
}
finally
{
mf.executor.shutdownNow();
}
}
public long longCalculation()
{
long result=LongStream.range(0, (long) Math.pow(2,32)).max().getAsLong();
System.out.println(new Date() + " Calculation result " + result);
return result;
}
}

Why worker thread transitions from CANCELLED to SCHEDULED skipping READY? (JavaFX2)

Update: I am finding the problem with other threads too; they enter Scheduled state but never transition to Running. why?
My program has a Service that uses a Task to connect to a device through the serial port.
In other words,
public class ConnectService extends Service<String> {
protected Task createTask() {
return new ConnectTask();
}
class ConnectTask extends Task<ObservableList<String>> {
#Override
protected ObservableList<String> call() throws Exception {
...
connect();
...
}
}
}
If a previous call to connect to the device got hung, then I want to cancel the task/thread and start over afresh in this attempt.
In order to do this,
if (connectService.getState() != Worker.State.READY) {
connectService.cancel();
}
connectService.restart();
However in the debugger I am finding that if the state is SCHEDULED, then the above code sends it to CANCELLED. But restart() will not send it to READY - instead it goes back to SCHEDULED - and call() does not get executed!
This seems to contradict the docs here
A reusable Worker will transition from CANCELLED, SUCCEEDED or FAILED
back to READY.
I tried
if (connectService.getState() != Worker.State.READY) {
connectService.cancel();
connectService.reset();
}
connectService.start();
Now state goes back to READY, but call() is never executed!
You need to add Worker.State.SCHEDULED to the states excluded from your if condition, i.e.
if (connectService.getState() != Worker.State.READY &&
connectService.getState() != Worker.State.SCHEDULED) {
connectService.cancel();
}
connectService.restart();
This is because the Worker will always transition from READY to SCHEDULED before it enters the RUNNING state. From the docs
However even in cases where the Worker is executed immediately, the
Worker will temporarily enter the SCHEDULED state before entering the
RUNNING state. That is, the transition is always from READY to
SCHEDULED to RUNNING (unless of course the Worker in cancelled).
If for some reason your working is stuck in the SCHEDULED state, it's likely that the cancel and restart just returns it to the same stuck state.
Also, (not seeing the rest of your code, so this is just extrapolation) the idea of interrupting it when you catch it running on the assumption that it is hung seems shaky, since it could be working well but taking longer than expected, or it could be hanging every time you call it. If there's no test you can run within connectService to determine whether it's hung or not, then I guess you're stuck with something like this, but it feels problematic.

MFC Threading Issue - The program doesnt end after all threads are completed

I have created a Single Dialog application which basically does a series of complex calculation. The application was first created as a Win32 console application and later I decided to add a progressbar and then I converted the console application to a Single Dialog based application. The dialog has a progressbar on it. in OnInitDialog() function of the dialog, I start the calculations. The calculations are running on a worker thread. This thread is created by calling _beginthreadex function. The progressbar is updated by the thread by posting messages to the Dialog by using PostMessage. After the thread has completed execution, I call CDialog::OnOK() function to close the dialog. The issue is that, even after the dialog is closed, the application is not end immediately. It takes nearly 2 seconds to close the application even though the dialog is closed.
Any help to solve this issue is highly appreciated.
Thanks.
It's because your worker thread is still running. The application will not terminate until all threads are finished running. Since your UI thread closes before the worker thread, the window may be hidden, but the process does not terminate until the worker thread has completed its work.
The worker thread might be still running. To make sure that the thread is stopped use events to signal . you can signal an event to kill the thread when the user presses close button in the dialog.
You can check whether the event is signaled inside your complex calculation (may be a loop) and break from it. Thus stopping the thread without any issues.
while(true)
{
//Some complex task
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(hwndShutdownEvent,0);
if (WAIT_OBJECT_0 == dwWaitResult)
{
break;
}
}

How to properly implement and close sleeping thread in a Windows DLL

I have a native Windows DLL written in C. This DLL is designed to be loaded (injected) in different Windos processes. This DLL creates some working threads that look like this:
while(1) {
// do work
Sleep(few secs);
}
The problem is if the process exits and DLL unloads while thread is in Sleep() it will crash the process when it comes back from Sleep (thread will try to execute code that is not there). I was thinking of using TerminateThread() with the DllUnload handler but MSDN says it should be used in most extreme cases only. For example - my threads use critical sections and the documentation says:
If the target thread owns a critical section, the critical section will not be released.
How do I cleanly close the thread that is sleeping when the DLL is unloading? Should I redesign my working threads to do work in some other way?
Create an event:
HANDLE threadTerminationEvent = CreateEvent(.....);
Use WaitForSingleObject instead of Sleep:
while (1)
{
...........
if (WaitForSingleObject(threadTerminationEvent, few secs) != WAIT_TIMEOUT)
break;
}
// release resources and end thread
Wait for the thread to end itself:
SetEvent(threadTerminationEvent); // “please, die”
WaitForSingleObject(hThread, INFINITE);

Resources