Room: application crashes on emulator - android-room

I am adding a second column to my room application. The application builds fine but fails on the emulator.
logcat
E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_0
Process: app.bluecoral.pbtracker, PID: 11773
java.lang.RuntimeException: Exception while computing database live data.
at androidx.room.RoomTrackingLiveData$1.run(RoomTrackingLiveData.java:92)
at androidx.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:139)
at androidx.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:119)
androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:452)
at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:275)
at androidx.room.RoomDatabase.query(RoomDatabase.java:304)
at androidx.room.util.DBUtil.query(DBUtil.java:54)
at app.bluecoral.pbtracker.PbDao_Impl$5.call(PbDao_Impl.java:102)
at app.bluecoral.pbtracker.PbDao_Impl$5.call(PbDao_Impl.java:99)
at androidx.room.RoomTrackingLiveData$1.run(RoomTrackingLiveData.java:90)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
PbDao
#Dao
interface PbDao {
#Query("SELECT * from pb_table ORDER BY pb, pb_value ASC")
fun getAlphabetizedPbs(): LiveData<List<Pb>>
#Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(pb: Pb)
#Query("DELETE FROM pb_table")
suspend fun deleteAll()
}

Related

Spring event multicaster strange behavior with transaction event listener

I am using application events in my service and decided to go for multicaster since I can set up the error handler and get the stacktrace in the console (normally runtime exceptions are not caught and are silently surpressed). So I defined my multicaster config as following:
#Configuration
class ApplicationEventMulticasterConfig {
companion object {
private val log = LoggerFactory.getLogger(ApplicationEventMulticasterConfig::class.java)
}
#Bean(name = ["applicationEventMulticaster"])
fun simpleApplicationEventMulticaster(multicasterExecutor: TaskExecutor): ApplicationEventMulticaster {
val eventMulticaster = SimpleApplicationEventMulticaster()
eventMulticaster.setTaskExecutor(multicasterExecutor)
eventMulticaster.setErrorHandler { throwable ->
log.error(throwable.stackTraceToString())
}
return eventMulticaster
}
#Bean(name = ["multicasterExecutor"])
fun taskExecutor(): TaskExecutor {
val executor = ThreadPoolTaskExecutor()
executor.corePoolSize = 4
executor.maxPoolSize = 40
executor.initialize()
return executor
}
}
Listener Case1:
#TransactionalEventListener
fun onEvent(event: Events.Created) {
Listener Case2:
#TransactionalEventListener(fallbackExecution=true)
fun onEvent(event: Events.Created) {
Publishing with multicaster.multicastEvent(Events.Created()). This simply does not work as expected, in case 1, the listener is not started at all (if transaction commits or rolls back) and in case 2 is listener triggered EACH time (in case of commit or failure).
If I delete the whole ApplicationEventMulticasterConfig everything is working fine but I do not have error handler set. Do you have any idea what could be wrong? It might be something with the way how I set up those beans.

Java client uses one thread for prompting in command line, and another for socket messaging

Java server-client program where server runs a thread for each client and the client interfaces with the user via a guided menu at the command line.
I trying to have the client main thread handle receiving messages from the server and associated processing including sending responses and generate a new thread to prompt the user.
My reasoning for this was the client could receive messages from the server while the menu is prompted and waiting for input. Here's the basics:
class Client {
Client() {
} //constructor
public static void main(String[] args) {
Client c = new Client();
//other things
MenuThread mt = new MenuThread();
mt.start();
//other things
}
class MenuThread extends Thread {
public MenuThread() {
} //constructor
#Override
public void run() {
//menu & other things
}
Also in my Client class main thread, an event happens and my MenuThread needs to reset. So I interrupt it and start a new one:
menuThread.interrupt();
menuThread = new MenuThread();
menuThread.start();
Now, I'm having weird problems at the command line, as if multiple MenuThreads are left running. (1) Does this Thread approach seem logical (unfamiliar with Runnable nuances)? (2) Any idea what would be causing what seems like concurrency problems? The interrupt and start a new thread seems like a viable approach to me to be implement in the Client class main thread to reset the menu that is displayed by MenuThread at the command line.

Asynctask (progressDialog) - Failed to set damage region EGL_BAD_ACCESS

Help me - I am really stuck on the following issue:
The exception is thrown outside the scope of JVM and cannot be handled unless you know the NDK.
03-23 17:48:24.463 18768-18913/se.android.appinfo E/Parcel: fcntl(F_DUPFD_CLOEXEC) failed in Parcel::read, i is 0, fds[i] is -1, fd_count is 1, error: Too many open files
03-23 17:48:24.464 18768-18913/se.android.appinfo I/OpenGLRenderer: Surface query width is 1440
03-23 17:48:24.464 18768-18913/se.android.appinfo A/OpenGLRenderer: Failed to set damage region on surface 0x7edceec8c0, error=EGL_BAD_ACCESS
03-23 17:48:24.467 18768-18913/se.android.appinfo A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 18913 (RenderThread)
I guess the last ones about EGL and OpenGL ES is relevant here?
I have struggled hours and googled about it and cannot find any solutions. And this problem is new to me - this has never occurred to me - I made apps before using Asynctask and showing a progressdialog while loading.
The crash occurs somewhere in between the mainthread and backgroundthread. It does not occur every time, maybe 50% or something. When the crash comes its when the doInBackground is done or almost done and onPostExecute is to be called.
Please - take a notice of my source and help me if you suspect anything that throws the exception (Fatal signal).
source - custom class extending AsyncTask
public class Async_loader extends AsyncTask <String, Integer, String> implements AppInfoRetriever.ProgressInterface {
private Context context;
private AppInfoRetriever appInfoRetriever;
private ProgressDialog progressDialog;
public Async_loader(Context context, AppInfoRetriever appInfoRetriever) {
this.context = context;
this.appInfoRetriever = appInfoRetriever;
this.appInfoRetriever.setProgressInterface(this);
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
public String doInBackground(String ... params) {
try {
appInfoRetriever.retrieve();
} catch(PackageManager.NameNotFoundException nnfe) {
nnfe.printStackTrace();
}
appInfoRetriever.splitToUserSystemApps();
return "loading done";
}
#Override
public void onProgressUpdate(final Integer ... values) {
progressDialog.setProgress(values[0]);
progressDialog.setMessage("parsing apps: " + values[0]);
}
public void onPostExecute(String result) {
System.err.println(result);
progressDialog.dismiss();
}
/**
* Callback från AppInfoRetriever
* #param nItems
* #param index
*/
#Override
public void appLoadingProgress(int nItems, int index) {
publishProgress(index);
}
}
Good to know: Since I want to decouple code I let the AppInfoRetriever parse the apps and while parsing sending (via an interface) information back to Async_loader. I thought this may be the problem but I've tried to lift in the code to Async_loader but no success.

Report metrics during shutdown of spring-boot app

I have a shutdownhook which is successfully executed, but the metrics is not reported. Any advice is appreciated! I guess the issues can be
StatsDMetricWriter might be disposed before the shutdown hook? How can I verify? Or is there a way to ensure the ordering of the configured singletons?
The time gap between metric generation and app shutdown < configured delay. I tried spawning a new Thread with Thread.sleep(20000). But it didn't work
The code snippets are as follows:
public class ShutDownHook implements DisposableBean {
#Autowired
private MetricRegistry registry;
#Override
public void destroy() throws Exception {
registry.counter("appName.deployments.count").dec();
//Spawned new thread here with high sleep with no effect
}
}
My Metrics Configuration for dropwizard is as below:
#Bean
#ExportMetricReader
public MetricRegistryMetricReader metricsDWMetricReader() {
return new MetricRegistryMetricReader(metricRegistry);
}
#Bean
#ExportMetricWriter
public MetricWriter metricWriter() {
return new StatsdMetricWriter(app, host, port);
}
The reporting time delay is set as 1 sec:
spring.metrics.export.delay-millis=1000
EDIT:
The problem is as below:
DEBUG 10452 --- [pool-2-thread-1] o.s.b.a.m.statsd.StatsdMetricWriter : Failed to write metric. Exception: class java.util.concurrent.RejectedExecutionException, message: Task com.timgroup.statsd.NonBlockingUdpSender$2#1dd8867d rejected from java.util.concurrent.ThreadPoolExecutor -- looks like ThreadPoolExecutor is shutdown before the beans are shutdown.
Any Suggestions please?
EDIT
com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsPoller.getCommandJson() has the following piece of code
json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster
I'm not sure how/why the numbers will add up? Where can I find that logic?

Hibernate LockMode expected behavior

#Repository
public class MyClass{
public int myFunction(Integer id){
Record x = recordDao.get(id,LockMode.UPGRADE);
int d = x.getProp();
x.setProp(d+1);
recordDao.update(z);
}
}
#Service
#Transactional
public class MyOtherClass{
#Autowired
private MyClass myClass;
public void myOtherFnx(Integer id){
try{
myClass.myFunction(id);
}catch(Exception e){
throw new RuntimeException(e.getMessage());
}
}
}
What happens when new MyOtherClass().myOtherFnx(3) was invoked at same time but at separate request/transactions.
I tried creating runnables and invoke myOtherFunx on separate threads to simulate concurrency. I was expecting to get RuntimeException but
so far I haven't notice getting any runtime exception even if i increase the threads running myOtherFunx to 50.
Can you explain to me why this happens? Or is my assumption that a runtime exception will occur. The case when I am expecting a runtime exception
is when multiple threads invoke myClass.myFunction(3) and the Record object retrieved on these threads are the same, let's say
id=3,prop=4. Since one of them gets the lock first, when threads try to update the record only one should update and others will throw exception since I am catching all Exception.
The first Thread will acquire the lock, and release it on commit or rollback.
While the first Thread is doing its work, the rest of threads will wait for the lock to be released.
After the lock has been released, the next Thread will acquire it, do the updates, commit, and so on...
If you want to get an exception, you will have to use the LockMode UPGRADE_NOWAIT.

Resources