I know that Java is no C, so no pointers and direct usable addresses but still I need it, because of the given library.
The library Andglk has been ported from native C and whoever did it, has the following constructor declaration in one of the classes:
public LineInputEvent(Window w, String s, int lineBuffer,
long maxLen, int dispatchRock, boolean unicode)
I now want to create one such event, but have no idea how to specify the lineBuffer. About the dispatchRock - it is also problematic but I believe it is not the bigger problem here.
Basically, this int lineBuffer (as the dispatchRock) is used one for all events during a session. One example is 1405421324 for all inputs.
About it (in the C documentation, there is for now almost nothing about andglk) is said:
This text will be placed in a buffer of your choice.
Any idea how can I specify it in Java for a given String?
EDIT:
This is from the andglk.c:
int andglk_loader_glk_MemoryStream_retainVmArray(JNIEnv *env, jobject this, int buffer, long length)
{
if (gli_register_arr) {
gidispatch_rock_t rock = gli_register_arr((void *)buffer, length, gidispatch_char_array);
return rock.num;
}
}
Related
Here is a version of implementation of function Atomic::cmpxchg used for CAS:
jbyte Atomic::cmpxchg(jbyte exchange_value, volatile jbyte* dest, jbyte compare_value) {
assert(sizeof(jbyte) == 1, "assumption.");
uintptr_t dest_addr = (uintptr_t)dest;
// look here
uintptr_t offset = dest_addr % sizeof(jint);
volatile jint* dest_int = (volatile jint*)(dest_addr - offset);
jint cur = *dest_int;
jbyte* cur_as_bytes = (jbyte*)(&cur);
jint new_val = cur;
jbyte* new_val_as_bytes = (jbyte*)(&new_val);
// ... and here
new_val_as_bytes[offset] = exchange_value;
while (cur_as_bytes[offset] == compare_value) {
jint res = cmpxchg(new_val, dest_int, cur);
if (res == cur) break;
cur = res;
new_val = cur;
new_val_as_bytes[offset] = exchange_value;
}
return cur_as_bytes[offset];
}
In the code above, I want to know what the use of offset actually is. I think we could simply and directly comapre cur_as_bytes and compare_value, without any offset. So why do we need it and how does it work? Is it for alignment? Thanks.
Yes, it is for alignment. The posted code implements a single-byte compare-exchange, using an already existing int-based compare-exchange.
This gives a few problems that the code needs to solve:
The int-based compare-exchange is restricted to reading int-aligned values, which means that you have to work out which of the (4?) bytes of the int you actually want to change. After all, the other bytes in the int must be unaffected
When you then actually do the compare-exchange, it is only a failure if the single byte you are trying to alter has been changed behind your back. If any of the other bytes in the int have changed, then that is only a failure for the int-cmpxchg, but not a failure for the byte-cmpxchg
The part before the while-loop handles the first part of that, by creating an int-aligned pointer that the int-value can be read from, and then setting up the "int we expect to see" and "int we want to change to" values.
The loop then handles the second part, where the algorithm attempts the int-cmpxchg, and then retries any failures as long as it is one of the other bytes that have been changed from expected.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
The method boolean regionMatches(int toffset, String other, int ooffset, int len) of java.lang.String is implemented as
public boolean regionMatches(int toffset, String other, int ooffset,
int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
Since there is an overloaded method covering the same functionality, why is this method not implemented as simple delegation, like
public boolean regionMatches(int toffset, String other, int ooffset, int len) {
return regionMatches(false, toffset, other, ooffset, len);
}
First, this is an implementation-dependent choice, so it might be possible to encounter alternative implementation actually doing this delegation you suggest. That’s why it is important to specify, which implementation you are referring to.
In case of Oracle’s JDK or OpenJDK, which seems to be the Java 8 implementation you’re referring to, the decision was most likely made for performance reasons. As you can see, the implementation of regionMatches with boolean ignoreCase parameter will re-check this parameter within the loop when two characters do not match.
It might have been the starting point for implementing both operations, but turned out to be a performance bottleneck for some cases. Usually, the decision to write a special implementation instead of handling an operation more generically, is made based on profiling widespread real life applications.
The specialized regionMatches implementation for the case sensitive match consists of a very short straight-forward loop over the character arrays, which can have a dramatic impact on the efficiency of the HotSpot optimizer. E.g. it might compile this loop to native code comparing more than one character at a time.
Newer JDKs had to adapt the code as, since Java 9, a byte[] array is used instead of a char[] array and might contain iso-latin-1 or utf-16 encoded data, so different scenarios have to be handled. The implementors took the opportunity to introduce delegation, though it is the other way round:
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
if (!ignoreCase) {
return regionMatches(toffset, other, ooffset, len);
}
// specialized case insensitive comparison follows
So now, you get the optimized case sensitive comparison whether you invoke regionMatches without the boolean parameter or with false. Further, the case insensitive match operation is also optimized in that the boolean parameter won’t be re-checked in a loop.
In the past I have written code which handles incoming data from a serial port. The data has a fixed format.
Now I want to migrate this code to java (android). However, I see many obstacles.
The actual code is more complex, but I have a simplified version here:
#define byte unsigned char
#define word unsigned short
#pragma pack(1);
struct addr_t
{
byte foo;
word bar;
};
#pragma pack();
bool RxData( byte val )
{
static byte buffer[20];
static int idx = 0;
buffer[idx++] = val;
return ( idx == sizeof(addr_t) );
}
The RxData function is called everytime a byte is received. When the complete chunk of data is in, it returns true.
Some of the obstacles:
The used data types are not available to java. In other threads it is recommended to use larger datatypes, but in this case this is not a workable solution.
The size of the structure is in this case exactly 3 bytes. That's also why the #pragma statement is important. Otherwise the C compiler might "optimize" it for memory use, with a different size as a result.
Java also doesn't have a sizeof function and I have found no alternative for this kind of situation.
I could replace the 'sizeof' with a fixed value of 3, but that would be very bad practice IMO.
Is it at all possible to write such a code in java? Or is it wiser to try to add native c source into Android Studio?
Your C code has its problems too. Technically, you do not know how big a char and a short is. You probably want uint8_t and uint16_t respectively. Also, I'm not sure how portable packing is.
In Java, you need a class. The class might as well tell you how many bytes you need to initialise it.
class Addr
{
private byte foo;
private short bar;
public final static int bufferBytes = 3;
public int getUnsignedFoo()
{
return (int)foo & 0xff;
}
public int getUnsignedBar()
{
return (int)bar & 0xffff;
}
}
Probably a class for the buffer too although there may already be a suitable class in the standard library.
class Buffer
{
private final static int maxSize = 20;
private byte[] bytes = new byte[maxSize];
private int idx = 0;
private bool rxData(byte b)
{
bytes[idx++] = b;
return idx == Addr.bufferBytes;
}
}
To answer the question about the hardcodedness of the 3, this is actually the better way to do it because your the specification of your protocol should say "one byte for foo and two bytes for bar" not "a packed C struct with a char and a short in it". One way to deserialise the buffer is like this:
public class Addr
{
// All the stuff from above
public Addr(byte[] buffer)
{
foo = buffer[0];
bar = someFunctionThatGetsTheEndiannessRight(buffer[1], buffer[2]);
}
}
TI have left the way bar is calculated deliberately vague because it depends on your platform as much as anything. You can do it simply with bit shifts e.g.
(((short)buffer[1] & 0xff) << 8) | ((short)buffer[2] & 0xff)
However, there are better options available. For example, you can use a java.nio.ByteBuffer which has the machinery to cope with endian isssues.
I am writing to offer an application in Java right now and instead of using the operator "+", the user of the application can literally use the word "add" to add two numbers together.
I'm quite stuck on how to do this because I can't really use a method in order to complete the function considering I'd have to type "add()" rather than just "add". Unless there is a way to execute a method without the parentheses. Would I have to write a completely new class or is there an easier way to do this?
Just a little explanation on what you could do based on what the user enters:
int x = get it from the user;
int y = get it from the user;
string operation = get it from the user;
Create separate methods for the operations (i.e add(int x, int y), multiply(int x, int y), etc..)
Then create a method thag gets the values (x, y, string) say.. you can call it calculate(int x, int y, string operation)
Then in the calculuate method have a switch statement:
switch(operation)
{
case "add":
add(x,y);
break;
case "multiply":
multiply(x,y);
break;
etc...
}
Well, got you something to think about :).
There's no way to do this in Java. You have two options:
1)Use a preprocessor.
2)Write it in a different language. You can write things in other languages and still have it compatible with Java classes and libraries.
The consensus in comments seems to be 'Why would you want to do this? It is slow and cumbersome'. While the latter part is true, it is commonly done. See ScriptEngine as an example. Here is a demo of the JavaScript ScriptEngine in an applet.
The reader might note that ScriptEngine is an interface, suggesting an answer of 'implement your own script engine, based on the rules required'. Whether or not it is a good idea to create another scripting language, is left as an exercise for the reader.
(An expansion on the idea presented by user710502)
You can use reflection.
double a = Double.parseDouble(some user input);
double b = Double.parseDouble(some user input);
String operation = some user input; // i.e. "add", "subtract"
Method operator = Calculations.class.getMethod(operation, double.class, double.class);
// NoSuchMethodException is thrown if method of operation name isn't found
double result = (Double) operator.invoke(null, a, b);
In some sort of calculations class:
public static double add(double a, double b) {
return a + b;
}
public static double subtract(double a, double b) {
return a - b;
}
// and so forth
I would like to build a FUSE-based underland filesystem application, in Java.
There are a few bindings library available on the web, Fuse-J, jnetfs, Fuseforjava, javafuse.
None of them seem really alive as of today, so I gave my first try to JavaFuse.
The interface we must implement is there:
http://code.google.com/p/javafuse/source/browse/fs/JavaFS.java
and I wanted to reproduce this fuse helloworld example.
Question: Is there any chance that this:
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
(void) offset;
(void) fi;
if(strcmp(path, "/") != 0)
return -ENOENT;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, hello_path + 1, NULL, 0);
return 0;
}
can be implemented by this java function:
public int readdir_pre(String path, long buf, long filler, int offset, Fuse_file_info info);
public int readdir_post(String path, long buf, long filler, int offset, Fuse_file_info info, int result);
Fuse_file_info
Maybe I missed something, but I can't see how to use filler to populate the directory content ...
There are other oddities just for this helloworld example, like:
public int read_post(String path, String buf, int size, int offset, Fuse_file_info info, int result);
which is supposed to fill buf with size bytes of data, whereas Java String are supposed to be immutable.
You can try jnr-fuse project.
The project uses JNR, so you achieve full JNI performance and ease of implementation.
An example of implementation hello-world filesystem filter.
I'm not exactly sure, what you are trying to do with the double function read_pre & read_post.
Though I guess, they represent pre-work and post-work. Maybe you can declare the normal readdir() and call you pre & post from inside? Passing the same arguments back & forth? Because you have to declare readdir() to the fuse_main().
And about the second thing with buffers, it just expects a byte holding storage. You can pass it character arrays, or anything with bytes in it, denoted by size_t size that represents the size of buffer. In helloworld.c, the string characters are copied to buffer through memcpy(). You can read bytes from file and pass them on as buffer along with appropriate length.
I'm new to FUSE and would like to know how it is to work using Java as compared to the standard C.