JNIEXPORT jobject JNICALL Java_org_apache_activemq_artemis_nativo_jlibaio_LibaioContext_newContext()

in src/main/c/org_apache_activemq_artemis_nativo_jlibaio_LibaioContext.c [550:639]


JNIEXPORT jobject JNICALL Java_org_apache_activemq_artemis_nativo_jlibaio_LibaioContext_newContext(JNIEnv* env, jobject thisObject, jint queueSize) {
    int i = 0;

    #ifdef DEBUG
        fprintf (stdout, "Initializing context\n");
    #endif

	struct io_control * theControl = (struct io_control *) malloc(sizeof(struct io_control));
    if (theControl == NULL) {
        throwOutOfMemoryError(env);
        return NULL;
    }

	int res = io_queue_init(queueSize, &theControl->ioContext);
	if (res) {
		// Error, so need to release whatever was done before
        io_queue_release(theControl->ioContext);
        free(theControl);

		throwRuntimeExceptionErrorNo(env, "Cannot initialize queue:", res);
		return NULL;
	}

    theControl->iocb = (struct iocb **)malloc((sizeof(struct iocb *) * (size_t)queueSize));
    if (theControl->iocb == NULL) {
        io_queue_release(theControl->ioContext);
        free(theControl);

        throwOutOfMemoryError(env);
        return NULL;
    }

    for (i = 0; i < queueSize; i++) {
        theControl->iocb[i] = (struct iocb *)malloc(sizeof(struct iocb));
        if (theControl->iocb[i] == NULL) {

           // It may not have been fully initialized, therefore limit the cleanup up to 'i' members.
           iocb_destroy_bounded(theControl, i);

           io_queue_release(theControl->ioContext);
           free(theControl);

           throwOutOfMemoryError(env);
           return NULL;
       }
    }
    theControl->queueSize = queueSize;


    res = pthread_mutex_init(&(theControl->iocbLock), 0);
    if (res) {
        iocb_destroy(theControl);

        io_queue_release(theControl->ioContext);
        free(theControl);

        throwRuntimeExceptionErrorNo(env, "Can't initialize mutext:", res);
        return NULL;
    }

    res = pthread_mutex_init(&(theControl->pollLock), 0);
    if (res) {
        iocb_destroy(theControl);

        io_queue_release(theControl->ioContext);
        free(theControl);

        throwRuntimeExceptionErrorNo(env, "Can't initialize mutext:", res);
        return NULL;
    }

    theControl->events = (struct io_event *)malloc(sizeof(struct io_event) * (size_t)queueSize);
    if (theControl->events == NULL) {
        iocb_destroy(theControl);

        io_queue_release(theControl->ioContext);
        free(theControl);

        throwRuntimeExceptionErrorNo(env, "Can't initialize mutext (not enough memory for the events member): ", res);
        return NULL;
    }


    theControl->iocbPut = 0;
    theControl->iocbGet = 0;
    theControl->used = 0;
    theControl->thisObject = (*env)->NewGlobalRef(env, thisObject);

    return (*env)->NewDirectByteBuffer(env, theControl, sizeof(struct io_control));
}