Function showing mysterious behaviors - java-8

I am developing an android application with kotlin assistance but the question is based on pure kotlin fundamentals. Below is the function which is showing some unusual behavior:
fun CatchThat(funct: () -> Unit){
try {
funct()
}catch (ex: Error){
ex.printStackTrace()
}
}
When I use it in my code
CatchThat {
// Proprietary Code goes in here
}
Debugger does not work properly(sometimes)
The proprietary code does not execute at all(sometimes)
Why is that behavior encountered or am I getting some concepts wrong(maybe lambdas). Any help or suggestions are heartily welcomed.(I am a tyro in kotlin)
EDIT The thing that I am doing in Proprietary code.
I am trying to invoke a Thread Pool that is in turn calling a web activity. This is the best and all I could explain about it. I am sorry for that.

try/catch will only work on the current thread. In your snippet, if some exception ocourrs in another thread, the try/catch won't work
For example:
try {
println("Hola mundo 1!")
println(5 / 0)
} catch (ex: Throwable) {
println("Oups! $ex")// will be printed
}
try {
Thread {
println("Hola mundo 2!")
println(5 / 0)
}.start()
} catch (ex: Throwable) {
println("Oups! $ex")// won't be printed
}
println("Hola mundo 3!")//The exception thrown in the external thread don't kill the current thread
For the debugging issues take a look to Android Studio threaded debugging

I am not sure if it sorts out the problem but it's just worth a try since all your efforts went in vein(and also because there is no error in your syntax).
I guess if debugger stops on wrong line(or sometimes doesn't work), it usually means that
something broken in the code cache .
Try invalidating Idea cache and restarting if you are using Idea of course.
And before doing that
I would also recommend to update Kotlin with the latest version.

Related

Multithreaded Use of Spring Pulsar

I am working on a project to read from our existing ElasticSearch instance and produce messages in Pulsar. If I do this in a highly multithreaded way without any explicit synchronization, I get many occurances of the following log line:
Message with sequence id X might be a duplicate but cannot be determined at this time.
That is produced from this line of code in the Pulsar Java client:
https://github.com/apache/pulsar/blob/a4c3034f52f857ae0f4daf5d366ea9e578133bc2/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java#L653
When I add a synchronized block to my method, synchronizing on the pulsar template, the error disappears, but my publish rate drops substantially.
Here is the current working implementation of my method that sends Protobuf messages to Pulsar:
public <T extends GeneratedMessageV3> CompletableFuture<MessageId> persist(T o) {
var descriptor = o.getDescriptorForType();
PulsarPersistTopicSettings settings = pulsarPersistConfig.getSettings(descriptor);
MessageBuilder<T> messageBuilder = Optional.ofNullable(pulsarPersistConfig.getMessageBuilder(descriptor))
.orElse(DefaultMessageBuilder.DEFAULT_MESSAGE_BUILDER);
Optional<ProducerBuilderCustomizer<T>> producerBuilderCustomizerOpt =
Optional.ofNullable(pulsarPersistConfig.getProducerBuilder(descriptor));
PulsarOperations.SendMessageBuilder<T> sendMessageBuilder;
sendMessageBuilder = pulsarTemplate.newMessage(o)
.withSchema(Schema.PROTOBUF_NATIVE(o.getClass()))
.withTopic(settings.getTopic());
producerBuilderCustomizerOpt.ifPresent(sendMessageBuilder::withProducerCustomizer);
sendMessageBuilder.withMessageCustomizer(mb -> messageBuilder.applyMessageBuilderKeys(o, mb));
synchronized (pulsarTemplate) {
try {
return sendMessageBuilder.sendAsync();
} catch (PulsarClientException re) {
throw new PulsarPersistException(re);
}
}
}
The original version of the above method did not have the synchronized(pulsarTemplate) { ... } block. It performed faster, but generated a lot of logs about duplicate messages, which I knew to be incorrect. Adding the synchronized block got rid of the log messages, but slowed down publishing.
What are the best practices for multithreaded access to the PulsarTemplate? Is there a better way to achieve very high throughput message publishing?
Should I look at using the reactive client instead?
EDIT: I've updated the code block to show the minimum synchronization necessary to avoid the log lines, which is just synchronizing during the .sendAsync(...) call.
Your usage w/o the synchronized should work. I will look into that though to see if I see anything else going on. In the meantime, it would be great to give the Reactive client a try.
This issue was initially tracked here, and the final resolution was that it was an issue that has been resolved in Pulsar 2.11.
Please try updating the Pulsar 2.11.

C++/WinRT BLE device watcher throws an "illegal state change" error when calling Start()

I'm using MFC/win32 but I couldn't find a good way to work with BLE devices. So while trying to work with C++?WinRT, I created a BluetoothLEAdvertisementWatcher object and checked that it was created. However when I run start, I get the error. I tried to include the Received and Stopped event handlers from the API documentation, but I'm not quite getting the hang of those so I took them out.
void bleConnect(HWND hWnd)
{
auto watcher = BluetoothLEAdvertisementWatcher(); // create BLE advertisement watcher
watcher.ScanningMode(BluetoothLEScanningMode::Active);
wprintf(L"ble watcher status: %ld\n", watcher.Status());
if (watcher.Status() == BluetoothLEAdvertisementWatcherStatus::Created)
{
watcher.Start(); // this causes the error
}
}
The error is impl::error_illegal_state_change = 0x8000000d : An illegal state change was requested. under the winrt/base.h generated file. I'm not sure what that really means. A little bit of searching that error has made me more confused.
I've tried to replicate something like this, but I haven't gotten anything to work.
I've also attempted to declare the bluetooth capability in my appxmanifest.xml however I'm not sure that had any effects on debugging my project. I use MakeAppx in command line to package my project using a custom manifest.xml, so I'm unsure how to include it while debugging.
I feel like I'm missing something. Thanks in advance.
Edit: Here's the full error, I missed this last time somehow. Microsoft C++ exception: winrt::hresult_illegal_method_call at memory location 0x00EFE6D0. Again, this exception is the Start() function, but I'm not sure what else I can do with this information.
I found another post that may or may not be a solution, I'll be looking into it. So far, I've inserted the handlers from that post and still ran into the same error.
To start the BluetoothLEAdvertisementWatcher, make sure that you register both Received() and Stopped() with handlers. The C++/WinRT docs DO NOT mention this, but you need both. Results may vary because I am working with a desktop app using win32/MFC.
Also as the documents mention, the handlers must have the correct arguments to function correctly. See here for details.
In the case of C++/WinRT, the handlers should look like:
void OnAdvertisementRecieved(winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher const& watcher,
winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementReceivedEventArgs const& args)
{
// handle received BLE advertisement
}
void OnAdvertisementStopped(winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher const& watcher,
winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcherStoppedEventArgs const& args)
{
// this is called when watcher is 'Stopped' (not 'Stopping')
}

ktor server - when to move to another coroutine context

This may be a question about coroutines in general, but in my ktor server (netty engine, default configuration) application I perform serveral asyncronous calls to a database and api endpoint and want to make sure I am using coroutines efficiently. My question are as follows:
Is there a tool or method to work out if my code is using coroutines effectively, or do I just need to use curl to spam my endpoint and measure the performance of moving processes to another context e.g. compute?
I don't want to start moving tasks/jobs to another context 'just in case' but should I treat the default coroutine context in my Route.route() similar to the Android main thread and perform the minimum amount of work on it?
Here is an rough example of the code that I'm using:
fun Route.route() {
get("/") {
call.respondText(getRemoteText())
}
}
suspend fun getRemoteText() : String? {
return suspendCoroutine { cont ->
val document = 3rdPartyLibrary.get()
if (success) {
cont.resume(data)
} else {
cont.resume(null)
}
}
}
You could use something like Apache Jmeter, but writing a script and spamming your server with curl seems also a good option to me
Coroutines are pretty efficient when it comes to context/thread switching, and with Dispatchers.Default and Dispatchers.IO you'll get a thread-pool. There are a couple of documentations around this, but I think you can definitely leverage these Dispatchers for heavy operations
There are few tools for testing endpoints. Jmeter is good, there are also command line tools like wrk, wrk2 and siege.
Of course context switching costs. The coroutine in routing is safe to run blocking operations unless you have the option shareWorkGroup set. However, usually it's good to use a separate thread pool because you can control it's size (max threads number) to not get you database down.

Php7 practices regarding Throwable errors

Long story short is that we've recently switched from php 5.6 to php 7. Although the application (a Magento 1.9 based app) seems to work accordingly after the switch, we have some shell scripts which somehow/sometimes die all of the sudden without knowing why:
Mage::log("doing something", null, 'custom.log', true); <- logged, see it
doSomething(); <- perfroms a service call, which looks like it's done properly
Mage::log("something done", null, 'custom.log', true); <- not logged
The problem in the above is that we have absolutely no error, warning, etc. so we cannot determine what happens. Since the changing of error handling in Php7, I assume that an error occurs (which previously was being logged in /var/log/...) and now is thrown as an Error exception, which based on Php7 specifications is not caught by a classic catch(Exception $e){} block. So my main questions regarding this whole situation is:
When switching from Php5.X to Php7, wouldn't it be a good practice to change the catch(Exception $e) with catch(Throwable $e) as Throwable covers both Excptions and new Errors? Otherwise, if I'm correct, one should add multiple "catch (Error $e)" blocks inside the code where this could occur in order to catch these error now.

Is it possible to add additional information for crashes handled by Xamarin.Insights analytics framework

I have an xamarin.android with xamarin.insights intergrated.
Right now every time I handle error manually (try/catch) I'm adding information about environment (staging/production):
try
{
ExceptionThrowingFunction();
}
catch (Exception exception)
{
exception.Data["Environment"] = "staging";
throw;
}
But this information is missing in case if error handled by xamarin.insights itself (in case of crash).
It is possible to add additional exception data in case of crash?
docs reference I used
From reading the docs page reference that you mentioned, I still get the impression that you have to call the .Report method as well as in:-
Insights.Report(exception, new Dictionary <string, string> {
{"Some additional info", "foobar"}
});
What I believe they are saying in this example:-
try {
ExceptionThrowingFunction();
}
catch (Exception exception) {
exception.Data["AccountType"] = "standard";
throw;
}
Is that you have the ability when any Exception is encountered, to package additional information that you can later send to the Insights server, as the Data property of the Exception is just a Key/Value Dictionary.
So if you had an Exception several layers deep, you can choose to re-throw the Exception with additional information contained within it that you will later send to the Insights server.
At a higher level, you can then take the Exception that was thrown deeper down the call-hierarchy and then call the Insights.Report, with:-
Insights.Report(
{the rethrown exception in your higher up try..catch block},
{rethrown exception}.Data
);
that will then send all the additional Key/Value information previously captured.
From seeing your last part of your question though it looks like you are interested in Insights handling and sending this additional .Data automatically should there be an unhandled exception.
If it is not currently being sent, then perhaps suggest to them that this can be sent also? As it sounds a feasible request for this to automatically be sent as well incase of an unhandled exception.
Update 1:-
Yes - I understand about the unhandled exception scenario now that you are referring to.
I have not dealt with this component directly, so there may be hooks / event handlers or something already defined where you can tap into this, and execute some custom code just prior to this being sent.
If this is not available, then perhaps suggest this to them to include as its a Beta product?
Alternatively, you could still achieve this yourself by capturing the unhandled exceptions just prior to them falling. You'd have to code this however on each platform.
For instance on Windows Phone in the App class there is Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) to which you could then supplement the Exception thrown with this extra .Data.
For Android you could take a look at this post that describes how to catch uncaughtException that will help you in capturing the unhandled exceptions.
Whether just supplementing the Exception in these handlers above is enough all depends on how they've written their hook into this, as to how well it behaves and whether it is executed first, prior to their implementation.
You will have to try and see if it does. If it doesn't behave well, allowing you to supplement extra data prior to the automatic call to Insights, you have another fallback solution, to just do the .Report call manually within these unhandled exception handlers yourself to make this work and supplement the extra .Data to achieve your aim.

Resources